Python错误集锦:with方法打开文件提示:ValueError: I/O operation on closed file.

原文链接:http://www.juzicode.com/archives/2749

错误提示:

使用with方法打开文件后,再次read()文件时提示:ValueError: I/O operation on closed file.

#juzicode.com/vx:桔子code
with open('example-r.txt','r') as fileobj:
    cont = fileobj.read()
    print(cont)
fileobj.read()
juzicode.com
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-36-9c9a170219a2> in <module>
      3     cont = fileobj.read()
      4     print(cont)
----> 5 fileobj.read()

ValueError: I/O operation on closed file.

 

可能原因:

1、使用with方法打开了文件,生成的文件操作实例在with语句之外是无效的,因为with语句之外文件已经关闭了。

 

 

解决方法:

1、第2个read()方法必须包含在with语句内部:

#juzicode.com/vx:桔子code
with open('example-r.txt','r') as fileobj:
    cont = fileobj.read()
    print(cont)
    fileobj.read()
posted @ 2020-12-20 12:26  桔子code  阅读(777)  评论(0编辑  收藏  举报