【问题标题】:Python closes file after a single write()Python 在一次 write() 后关闭文件
【发布时间】: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()一起使用时,上下文管理器会自动关闭文件

标签: python file file-io


【解决方案1】:

你搞错了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 操作。

【讨论】:

    猜你喜欢
    • 2013-05-02
    • 1970-01-01
    • 2021-10-31
    • 2015-03-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-28
    • 1970-01-01
    • 2022-12-29
    相关资源
    最近更新 更多