Python ValueError:已关闭文件的 I/O 操作。示例教程不起作用
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28528255/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Python ValueError: I/O operation on closed file. sample tutorial not working
提问by Riaz Ladhani
I am following a tutorial to learn to read and write to a file. I am getting the following error. I do not understand why.
我正在按照教程学习读写文件。我收到以下错误。我不理解为什么。
C:\Python27\python.exe "C:/Automation/Python/Write to files/test3.py"
Traceback (most recent call last):
File "C:/Automation/Python/Write to files/test3.py", line 8, in <module>
f.read('newfile.txt', 'r')
ValueError: I/O operation on closed file
My code is
我的代码是
f = open("newfile.txt", "w")
f.write("hello world\n")
f.write("Another line\n")
f.close()
f.read('newfile.txt', 'r')
print f.read()
I have tried to put f.close
at the bottom of the code but I still get the same error.
我试图放在f.close
代码的底部,但我仍然遇到同样的错误。
The write part works if I comment out the f.read
. It is failing on the f.read
part.
如果我注释掉f.read
. 它在这方面失败了f.read
。
采纳答案by Bhargav Rao
The line after f.close()
that is f.read('newfile.txt', 'r')
should be f = open('newfile.txt', 'r')
.
后该生产线f.close()
是f.read('newfile.txt', 'r')
应该f = open('newfile.txt', 'r')
。
That is
那是
f = open('newfile.txt', 'r')
print f.read()
f.close()
After which you need to add f.close()
again.
之后您需要f.close()
再次添加。
Small Note
小笔记
As in Python, the default value for 2nd arg of open
is r
, you can simple do open('newfile.txt')
在 Python 中,第二个参数的默认值open
是r
,你可以简单地做open('newfile.txt')
回答by paul100
As illustrated above when you closed the file you need to open your file so that you can read it
如上图所示,当您关闭文件时,您需要打开文件才能阅读它
f = open('newfile.txt', 'r')
print f.read()
f.close()
回答by Rishabh
You can't perform I/O operation on file_obj after closing it i.e.
关闭 file_obj 后不能对它执行 I/O 操作,即
file_obj.close()
So if you want to open the same file do:
因此,如果您想打开相同的文件,请执行以下操作:
if(file_obj.closed):
file_obj = open(file_obj.name, file_obj.mode)
print (file.obj.read())
file_obj.close()