RE: Why is try...except in my code not working (gzip/text files) ?

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Barak, Ron

    #1

    RE: Why is try...except in my code not working (gzip/text files) ?

    Thanks Gabriel,
    Okay, I get it: I was under the impression that the format check would be done on the open.
    Bye,
    Ron.

    -----Original Message-----
    From: Gabriel Genellina [mailto:gagsl-py2@yahoo.com.a r]
    Sent: Thursday, November 20, 2008 02:06
    To: python-list@python.org
    Subject: Re: Why is try...except in my code not working (gzip/text files) ?

    En Wed, 19 Nov 2008 13:25:03 -0200, Barak, Ron <Ron.Barak@lsi. com>
    escribió:
    I need to read a file that is either a gzip or a text file (on both
    *nix and Windows).
    Since I didn't find a way to determine a file type, I thought of using
    the following:
    >
    import gzip
    >
    FILE = "../dpm/save_state-ssp8400-F0023209_080723-110131/top.1"
    #FILE =
    "../dpm/save_state-ssp8400-F0023209_080723-110131/var/log/sac.log.0.gz"
    >
    try:
    file = gzip.GzipFile(F ILE, "r") except IOError:
    file = open(FILE, "r")
    >
    print file.read()
    >
    >
    Strangely, when FILE is a gzip file, all is fine.
    But, when FILE is a text file (as in the above code), I get the
    following:
    >
    $ python ./gzip_try.py
    Traceback (most recent call last):
    File "./gzip_try.py", line 11, in <module>
    print file.read() <<<============ =======
    File "c:\Python25\li b\gzip.py", line 220, in read
    self._read(read size)
    File "c:\Python25\li b\gzip.py", line 263, in _read
    self._read_gzip _header()
    File "c:\Python25\li b\gzip.py", line 164, in _read_gzip_head er
    raise IOError, 'Not a gzipped file'
    IOError: Not a gzipped file
    >
    Can you explain why the try...except in my code does not work ?
    Or, back to my original problem: how do I deal with a file whether
    it's a text file or a gzip file ?
    Note *where* the exception is raised. Until something is actually read, no check is made for the file format.

    --
    Gabriel Genellina


Working...