【发布时间】:2014-10-24 18:52:49
【问题描述】:
我想编写一个能够编写 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
我假设它正在尝试关闭已经关闭的文件。它是否正确?如果是这样,关闭文件的正确方法是什么?
【问题讨论】:
-
你也有一个
__del__方法,不是吗。 -
你在
with之外有for吗? -
@Kasra:这有什么关系?
-
我在打开文件
with时看到此错误,然后不要在with中写入其他部分代码
标签: python file-io destructor