我正在学习阅读和写入文件的教程。 我收到以下错误。我不明白为什么。
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
我的代码是
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()
我试图将f.close
放在代码的底部,但我仍然遇到同样的错误。
如果我注释掉f.read
,则写入部分有效。它在f.read
部分失败了。
答案 0 :(得分:6)
f.close()
f.read('newfile.txt', 'r')
之后的行应为f = open('newfile.txt', 'r')
。
那是
f = open('newfile.txt', 'r')
print f.read()
f.close()
之后您需要再次添加f.close()
。
小笔记
与在Python中一样,open
的第二个arg的默认值为r
,您可以简单地执行open('newfile.txt')
答案 1 :(得分:2)
关闭后,您无法对file_obj执行I / O操作,即
file_obj.close()
因此,如果要打开相同的文件,请执行以下操作:
if(file_obj.closed):
file_obj = open(file_obj.name, file_obj.mode)
print (file.obj.read())
file_obj.close()
答案 2 :(得分:1)
如上图所示,当您关闭文件时,您需要打开文件以便阅读
f = open('newfile.txt', 'r')
print f.read()
f.close()