我想编写一个能够编写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 > ignored
我假设它正在尝试关闭文件,因为它已经关闭.它是否正确?如果是这样,关闭文件的正确方法是什么?