2
我使用Python版本2.7.10与macOS Sierra 10.12.16和Xcode 8.3.3 在演示程序中,我想在文件中写入2行文本。 这应该分两步完成。在第一步中调用方法openNewFile()。该文件是使用open命令创建的,并且一行文本被写入该文件。文件句柄是方法的返回值。 在第二步,方法closeNewFile(fH)与文件句柄fH作为输入参数被调用。应将第二行文本写入文件,并关闭文件。然而,这将导致一个错误信息:Python在单次写入后关闭文件()
Traceback (most recent call last):
File "playground.py", line 23, in <module>
myDemo.createFile()
File "playground.py", line 20, in createFile
self.closeNewFile(fH)
File "playground.py", line 15, in closeNewFile
fileHandle.writelines("Second line")
ValueError: I/O operation on closed file
Program ended with exit code: 1
在我看来,从一个方法处理的文件转移到另一个可能是问题。
#!/usr/bin/env python
import os
class demo:
def openNewFile(self):
currentPath = os.getcwd()
myDemoFile = os.path.join(currentPath, "DemoFile.txt")
with open(myDemoFile, "w") as f:
f.writelines("First line")
return f
def closeNewFile(self, fileHandle):
fileHandle.writelines("Second line")
fileHandle.close()
def createFile(self):
fH = self.openNewFile()
self.closeNewFile(fH)
myDemo = demo()
myDemo.createFile()
我做错了什么? 这个问题怎么解决?
你能提供打开/关闭文件的代码吗? – AK47
当您使用open()时,上下文管理器会自动关闭文件 – AK47