首页 > 解决方案 > 将数据写入 csv 文件时出错,ValueError: I/O operation on closed file

问题描述

这是一个代码:

 import pandas as pd
    import csv
    with open('reviews.csv') as myFile:  
        reader = csv.reader(myFile)w
    with open('bow.csv','a',newline="") as file:
        handler= csv.writer(file)
        for rowdata in reader:
            handler.writerow({rowdata,'asd'})

错误是 ValueError:对已关闭文件的 I/O 操作。

标签: pythoncsv

解决方案


csv.reader()只能从打开的文件中读取。当您退出第一个with块时,myFile它会自动关闭,因此reader无法再从中读取。

您需要在读取输入文件时保持打开状态。

import pandas as pd
import csv
with open('reviews.csv') as myFile:  
    reader = csv.reader(myFile)
    with open('bow.csv','a',newline="") as file:
        handler= csv.writer(file)
        for rowdata in reader:
            handler.writerow({rowdata,'asd'})

您还可以在单​​个with语句中打开多个文件,因此您不需要嵌套它们。

with open('reviews.csv') as myFile, open('bow.csv','a',newline="") as file:  
    reader = csv.reader(myFile)w
    handler= csv.writer(file)
    for rowdata in reader:
        handler.writerow({rowdata,'asd'})

推荐阅读