[Tutor] GzipFile has no attribute '__exit__'
Kent Johnson
kent37 at tds.net
Mon Nov 16 12:41:38 CET 2009
On Mon, Nov 16, 2009 at 5:58 AM, Stephen Nelson-Smith
<sanelson at gmail.com> 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?
gzip.open() doesn't support the context manager protocol needed for it
to be used in a 'with' statement. Just do this old-style:
output = gzip.open('/tmp/merged_log.gz', 'w')
try:
for stamp, line in merged_log:
output.write(line)
finally:
output.close()
See PEP 343 this explanation of context managers if you want to know
why you got this specific error:
effbot.org/zone/python-with-statement.htm
http://www.python.org/dev/peps/pep-0343/
Kent
More information about the Tutor
mailing list