python - 值错误 : I/O operation on closed file

标签 python csv file-io io

import csv    

with open('v.csv', 'w') as csvfile:
    cwriter = csv.writer(csvfile, delimiter=' ', quotechar='|', quoting=csv.QUOTE_MINIMAL)

for w, c in p.items():
    cwriter.writerow(w + c)

这里,p是字典,wc都是字符串。

当我尝试写入文件时,它会报告错误:

ValueError: I/O operation on closed file.

最佳答案

正确缩进;您的 for 语句应该在 with 内 block :

import csv    

with open('v.csv', 'w') as csvfile:
    cwriter = csv.writer(csvfile, delimiter=' ', quotechar='|', quoting=csv.QUOTE_MINIMAL)

    for w, c in p.items():
        cwriter.writerow(w + c)

with block 之外,文件被关闭。

>>> with open('/tmp/1', 'w') as f:
...     print(f.closed)
... 
False
>>> print(f.closed)
True

关于python - 值错误 : I/O operation on closed file,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18952716/

相关文章:

Python 多处理队列 NotImplementedError macOS

python - 模块未找到错误 : No module named 'mnist'

mysql - 按列分组查询,然后将多行导出为单行

scala - 在 Scala 2.8 中,如何向文件写入(追加)一行?我应该使用 Java 类(class)还是为此使用原生的 Scala 函数?

c - 用C读取300MB文本文件

python - Word2VecKeyedVectors 的对象没有属性 'index_to_key'

php - CSV文件上传到php mysql数据库

c# - 替换 C# 读取的 CSV 文件中的所有空值

windows - 什么是 `Zone.Identifier` 文件,如何防止创建它们?

python - 遍历 Python 字典中的值列表