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

phy*_*ion 4 python file-io destructor

我想编写一个能够编写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')
Run Code Online (Sandbox Code Playgroud)

我用这个类:

with ColorWheel(params) as cw:
    cw.wheel()
Run Code Online (Sandbox Code Playgroud)

该文件完全按照我的预期编写.但是,当我运行它时,我收到以下错误:

Exception ValueError: 'I/O operation on closed file' in <bound method ColorWheel.__del__ of ColorWheel.ColorWheel object at 0x0456A330>> ignored
Run Code Online (Sandbox Code Playgroud)

我假设它正在尝试关闭文件,因为它已经关闭.它是否正确?如果是这样,关闭文件的正确方法是什么?

Mar*_*ers 5

您还有一种__del__方法在关闭文件后尝试写入该文件.当cw超出范围并被清理时,将__del__调用钩子并且您似乎尝试在该点写入文件.

您可以测试文件是否已关闭:

if not self.f.closed:
    # do something with file
Run Code Online (Sandbox Code Playgroud)