在__exit__或__del__方法中关闭文件?

5 投票
1 回答
7533 浏览
提问于 2025-04-19 01:45

我想写一个可以生成HTML文件的类。现在我有了以下的基本结构:

class ColorWheel(object):
    def __init__(self, params):
        self.params = params

    def __enter__(self):
        self.f = open('color_wheel.html', 'w')
        self._write_header()
        return self

    def __exit__(self, type_unused, value_unused, traceback_unused):
        self._write_footer()
        self.f.close()

    def wheel(self):
        # Code here to write the body of the html file
        self.f.write('BODY HERE')

我用这个类的方式是:

with ColorWheel(params) as cw:
    cw.wheel()

文件的内容完全按照我的预期写好了。但是,当我运行这个程序时,我遇到了以下错误:

Exception ValueError: 'I/O operation on closed file' in <bound method ColorWheel.__del__ of ColorWheel.ColorWheel object at 0x0456A330>> ignored

我猜测它是在尝试关闭一个已经关闭的文件。这是对的吗?如果是的话,正确的关闭文件的方法是什么呢?

1 个回答

7

你还有一个 __del__ 方法,它试图在文件关闭后继续 写入 文件。当 cw 超出作用域并被清理时,__del__ 方法会被调用,这时你似乎在尝试向文件写入内容。

你可以用以下方法检查文件是否已经关闭:

if not self.f.closed:
    # do something with file

撰写回答