Closing a file in a class method __exit__ or __del__?

I want to write a class capable of writing an html file. I now have the following skeleton:

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')

      

I am using this class:

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

      

The file is written exactly as I expect. However, when I run this, I get the following error:

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

      

I am assuming that it is trying to close the file while it is already closed. It's right? If so, what would be the correct way to close the file?

+3


source to share


1 answer


You also have a method __del__

that tries to write to the file after it is closed. When it cw

goes out of scope and clears, the trick is called __del__

and you try to write it to the file at that point.

You can check if the file is already closed with



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

      

+5


source







All Articles