Python在单个write()之后关闭文件

Hei*_* M. 2 python file-io file

我正在使用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 line")
        fileHandle.close()

    def createFile(self):
        fH = self.openNewFile()
        self.closeNewFile(fH)

myDemo = demo()
myDemo.createFile()
Run Code Online (Sandbox Code Playgroud)

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

cs9*_*s95 10

你错了什么with....as.这段代码是罪魁祸首:

 with open(myDemoFile, "w") as f:
    f.writelines("First line")
    return f
Run Code Online (Sandbox Code Playgroud)

在返回之前,with 关闭文件,因此您最终从函数返回一个已关闭的文件.

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

f = open(myDemoFile, "w") 
f.writelines("First line")
return f
Run Code Online (Sandbox Code Playgroud)

这一改进将不会摆脱你的上下文管理器,但执行所有的I/O 的上下文管理器.没有单独的打开和写入功能,也没有分割I/O操作.