我正在学习如何阅读和写入文件的教程.我收到以下错误.我不懂为什么.
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.
后该生产线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的默认值open是r,你可以简单地做open('newfile.txt')
| 归档时间: |
|
| 查看次数: |
30083 次 |
| 最近记录: |