我正在使用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
Run Code Online (Sandbox Code Playgroud)
在我看来,将文件从一种方法处理到另一种方法可能是问题所在.
#!/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 …Run Code Online (Sandbox Code Playgroud)