csv python上已关闭文件的I / O操作

时间:2018-07-18 21:03:56

标签: python python-3.x

我正在处理python3项目,尝试在CSV文件上写入时遇到错误。

with open('infile.csv', 'r') as f:
    reader = csv.reader(f)


# manipulate the data

with open('outfile.csv', 'w') as fl:
    writer = csv.writer(fl)
    for row in reader:
        writer.writerow(row)

我遇到I/O operation on closed file on csv python个问题。我需要首先创建outfile.csv吗?我不确定吗?

1 个答案:

答案 0 :(得分:3)

由于使用的是上下文管理器,因此infile超出作用域时将被关闭。

解决方案是

with open('infile.csv', 'r') as f:
    reader = csv.reader(f)


    # manipulate the data

    with open('outfile.csv', 'w') as f:
        writer = csv.writer(f)
        for row in reader:
             writer.writerow(row)

编辑这是一种更简洁有效的方法

with open('infile.csv', 'r') as fin, open("outfile.csv" , "w") as fout:
    reader = csv.reader(fin)
    writer = csv.writer(fout) 
    for row in reader:        
        writer.writerow(row)