[Tutor] GzipFile has no attribute '__exit__'

Dave Angel davea at ieee.org
Mon Nov 16 12:54:49 CET 2009

Stephen Nelson-Smith wrote:
> I'm trying to write a gzipped file on the fly:
> merged_log = merge(*logs)
> with gzip.open('/tmp/merged_log.gz', 'w') as output:
>     for stamp, line in merged_log:
>         output.write(line)
> But I'm getting:
> Traceback (most recent call last):
>   File "./magpie.py", line 72, in <module>
>     with gzip.open('/tmp/merged_log.gz', 'w') as output:
> AttributeError: GzipFile instance has no attribute '__exit__'
> What am I doing wrong, and how do I put it right?
> S.
(I get the same result in CPython 2.6, but you should have told your 
python version and OS, just so people can tell you version-specific 

In order to use the "with" syntax with an object of a particular class, 
that class has to support the Context Manager protocol, which includes 
both __enter__() and __exit__() methods.  I don't know why the system 
checks first for __exit__(), but there you have it.

GzipFile() class doesn't have such methods (in version 2.6), and 
therefore doesn't support the Context Manager.  So you have to do it the 
"old fashioned" way, with explicit close() method, and a 
try/except/finally.  And unlike regular text files, I don't expect 
you'll find a new file at all usable, if it wasn't properly closed.

Alternatively, you could subclass it, and write your own.  At a minimum, 
the __exit__() method should close() the stream.


More information about the Tutor mailing list