CSV文件引发ValueError: readline of closed file

先贴代码:

with open(infile, "r+b") as tsv_in_file:
    reader = csv.DictReader(tsv_in_file, delimiter='\t', fieldnames=FIELDNAMES)   
for item in tqdm(reader):  
    print(item)

报错:

ValueError: readline of closed file

原因:

使用with open 打开文件时,文件只能在当前函数下使用

with open(infile, "r+b") as tsv_in_file:

报错原因:当执行循环的时候由于不在with open下执行,所以循环时之前加载的文件已经关闭了

修改:

with open(infile, "r+b") as tsv_in_file:
    reader = csv.DictReader(tsv_in_file, delimiter='\t', fieldnames=FIELDNAMES)   
    for item in tqdm(reader):  
        print(item)

如果还报错,可以把文档读取格式转为“r”

你可能感兴趣的:(python,编程语言)