当前位置: 代码迷 >> 综合 >> CSV文件引发ValueError: readline of closed file
  详细解决方案

CSV文件引发ValueError: readline of closed file

热度:52   发布时间:2023-12-27 13:10:06.0

先贴代码:

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”

  相关解决方案