html 파일을 작성할 수있는 클래스를 작성하고 싶습니다.클래스 __exit__ 또는 __del__ 메소드에서 파일 닫기?
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__' 방법을하지 않습니다 있습니다. –
'와 함께'밖에'for'가 있습니까? – Kasramvd
@ 카스라 : 그게 무슨 상관이 있습니까? –