2017-08-27 93 views
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() 

我做错了什么? 这个问题怎么解决?

+0

你能提供打开/关闭文件的代码吗? – AK47

+0

当您使用open()时,上下文管理器会自动关闭文件 – AK47

回答

10

你误解了with....as的功能。此代码是这里的罪魁祸首:

with open(myDemoFile, "w") as f: 
    f.writelines("First line") 
    return f 

就在返回之前,with关闭文件,所以你最终从函数返回一个关闭的文件。

我应该添加 - 在一个函数中打开一个文件并返回它而不关闭它(你的实际意图是什么)是主要的代码异味。这就是说,修复这一问题将是摆脱with...as上下文管理的:

f = open(myDemoFile, "w") 
f.writelines("First line") 
return f 

到这方面的一个改进是摆脱你的上下文管理的,但开展所有您的I/O 之内的上下文管理器。不要有单独的函数来打开和写入,也不要分割您的I/O操作。