Python ValueError:关闭文件的I/O操作.示例教程不起作用

Ria*_*ani 5 python

我正在学习如何阅读和写入文件的教程.我收到以下错误.我不懂为什么.

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
Run Code Online (Sandbox Code Playgroud)

我的代码是

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()
Run Code Online (Sandbox Code Playgroud)

我试图放在f.close代码的底部,但我仍然得到相同的错误.

如果我注释掉,写部分可以工作f.read.它失败了f.read.

Bha*_*Rao 6

后该生产线f.close()f.read('newfile.txt', 'r')应该f = open('newfile.txt', 'r').

那是

f = open('newfile.txt', 'r')
print f.read()
f.close()
Run Code Online (Sandbox Code Playgroud)

之后你需要f.close()再次添加.

小笔记

和Python一样,第二个arg的默认值openr,你可以简单地做open('newfile.txt')