[Tutor] GzipFile has no attribute '__exit__'
Sander Sweers
sander.sweers at gmail.com
Mon Nov 16 13:15:32 CET 2009
2009/11/16 Dave Angel <davea at ieee.org>:
> Alternatively, you could subclass it, and write your own. At a minimum, the
> __exit__() method should close() the stream.
This triggered my to dig into this a bit. This is not fixed untill
python 3.1 but seems easilly added to the ZipFile class. My attempt to
backport this from python 3.1's gzip.py below seems to work.
Greets
Sander
import gzip
class myGzipFile(gzip.GzipFile):
def __enter__(self):
if self.fileobj is None:
raise ValueError("I/O operation on closed GzipFile object")
return self
def __exit__(self, *args):
self.close()
zfilepath = r'C:\test.gz'
s = 'This is a test'
with myGzipFile(zfilepath,'w') as output:
output.write(s)
More information about the Tutor
mailing list