[Tutor] gzip file close

Danny Yoo dyoo at hkn.eecs.berkeley.edu
Tue Aug 10 22:02:25 CEST 2004



On Tue, 10 Aug 2004, David Rock wrote:

> The first file is gzipped, the second is not. The try block I am trying
> to use looks like this:
>
>     try:
>         fp_input = gzip.open( inputfile, 'rb' )
>     except:
>         fp_input = open( inputfile, 'rb' )
>
> The idea was that if the file is not gzipped, it would do the second
> file open instead.


Hi David,


The assumption that you're making here is that gzip.open() raises an
exception on a non-gzipped file, but this might not be true.


For example:

###
>>> from StringIO import StringIO
>>> bogusData = StringIO("I am not a zipped file")
>>> bogusData.seek(0)
>>>
>>> import gzip
>>> unzippedFile = gzip.GzipFile(fileobj=bogusData)
>>> unzippedFile.read(1)
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
  File "/usr/lib/python2.3/gzip.py", line 224, in read
    self._read(readsize)
  File "/usr/lib/python2.3/gzip.py", line 260, in _read
    self._read_gzip_header()
  File "/usr/lib/python2.3/gzip.py", line 161, in _read_gzip_header
    raise IOError, 'Not a gzipped file'
IOError: Not a gzipped file
###


So it appears that gzip.GzipFile only starts reading the source file on a
request for data, and not on open().


Hope this helps!



More information about the Tutor mailing list