【发布时间】:2017-08-27 20:52:48
【问题描述】:
我将 Python 版本 2.7.10 与 macOS Sierra 10.12.16 和 Xcode 8.3.3 一起使用 在演示程序中,我想在一个文件中写入 2 行文本。 这应该分两步完成。在第一步中,方法 openNewFile() 被调用。使用 open 命令创建文件,并将一行文本写入文件。文件句柄是方法的返回值。 在第二步中,以文件句柄 fH 作为输入参数的方法 closeNewFile(fH) 被调用。应将第二行文本写入文件并关闭文件。但是,这会导致错误消息:
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()
我做错了什么? 如何解决这个问题?
【问题讨论】:
-
你能提供打开/关闭文件的代码吗?
-
与open()一起使用时,上下文管理器会自动关闭文件