physicalattraction
physicalattraction

Reputation: 6858

Closing a file in Class __exit__ or __del__ method?

I want to write a class that is able to write 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 use this class with:

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

The file is exactly written as I expect it to be. 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 assume it is trying to close the file while it has already been closed. Is this correct? If so, what would be the proper way to close the file?

Upvotes: 5

Views: 8028

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1124758

You also have a __del__ method trying to write to the file after closing it. When cw goes out of scope and is cleaned up, the __del__ hook is called and you appear to try and write to the file at that point.

You can test if a file is closed already with:

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

Upvotes: 7

Related Questions