python - 将数据写入 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 操作。
解决方案
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'})
推荐阅读
- zend-framework - 需要知道 Zend Framework 1 的确切版本
- python - 映射和 lambda 函数的 Python 字符串问题
- python - 查找背景的最佳方法 - 图像处理 Python
- html - 导轨排除多个字符串
- javascript - 如何在Javascript中使对象可下标?
- android - 在 FragmentPagerAdapter 内的设备旋转后 FindViewById 为空
- javascript - 如何通过选择浏览器建议来保持悬停效果?
- javascript - 如何测试 JavaScript 的 Intl.NumberFormat()
- php - 如何在 Laravel 6 中删除数据库?
- android - Kotlin - 从网络提供商获取位置的问题