我正在处理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
吗?我不确定吗?
答案 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)