原文链接: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()