ValueError : 关闭文件的 I/O 操作 [英] ValueError : I/O operation on closed file

查看:34
本文介绍了ValueError : 关闭文件的 I/O 操作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

导入csv使用 open('v.csv', 'w') 作为 csvfile:cwriter = csv.writer(csvfile, delimiter='', quotechar='|', quoting=csv.QUOTE_MINIMAL)对于 p.items() 中的 w、c:cwriter.writerow(w + c)

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

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

ValueError: 关闭文件的 I/O 操作.

解决方案

缩进正确;您的 for 语句应该在 内与块:

导入csv使用 open('v.csv', 'w') 作为 csvfile:cwriter = csv.writer(csvfile, delimiter='', quotechar='|', quoting=csv.QUOTE_MINIMAL)对于 p.items() 中的 w、c:cwriter.writerow(w + c)

with 块之外,文件被关闭.

<预><代码>>>>with open('/tmp/1', 'w') as f:...打印(f.关闭)...错误的>>>打印(f.关闭)真的

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)

Here, p is a dictionary, w and c both are strings.

When I try to write to the file it reports the error:

ValueError: I/O operation on closed file.

解决方案

Indent correctly; your for statement should be inside the 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)

Outside the with block, the file is closed.

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

这篇关于ValueError : 关闭文件的 I/O 操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆