<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML><HEAD><TITLE></TITLE>
<META http-equiv=Content-Type content="text/html; charset=us-ascii">
<META content="MSHTML 6.00.2900.3429" name=GENERATOR></HEAD>
<BODY><!-- Converted from text/plain format -->
<P>Hi,<BR><BR>I need to read a file that is either a gzip or a text file (on
both *nix and Windows).<BR>Since I didn't find a way to determine a file type, I
thought of using the following:<BR><BR><FONT size=2><FONT
face="Courier New">import gzip</FONT></FONT></P>
<P><FONT size=2><FONT face="Courier New">FILE =
"../dpm/save_state-ssp8400-F0023209_080723-110131/top.1"<BR>#FILE =
"../dpm/save_state-ssp8400-F0023209_080723-110131/var/log/sac.log.0.gz"</FONT></FONT></P>
<P><FONT size=2><FONT
face="Courier New">try:<BR> file =
gzip.GzipFile(FILE, "r")<BR>except
IOError:<BR> file = open(FILE,
"r")</FONT></FONT></P>
<P><FONT size=2><FONT face="Courier New">print
file.read()<BR></FONT><BR><BR></FONT>Strangely, when FILE is a gzip file, all is
fine.<BR>But, when FILE is a text file (as in the above code), I get the
following:<BR><BR><FONT size=2><FONT face="Courier New">$ python
./gzip_try.py<BR>Traceback (most recent call last):<BR> File
"./gzip_try.py", line 11, in <module><BR> print
file.read()<BR> File "c:\Python25\lib\gzip.py", line 220, in
read<BR> self._read(readsize)<BR> File
"c:\Python25\lib\gzip.py", line 263, in _read<BR>
self._read_gzip_header()<BR> File "c:\Python25\lib\gzip.py", line 164, in
_read_gzip_header<BR> raise IOError, 'Not a gzipped
file'<BR>IOError: Not a gzipped file<BR></FONT></FONT><BR><FONT
color=#0000ff>Can you explain why the try...except in my code does not work
?<BR>Or, back to my original problem: how do I deal with a file
whether it's a text file or a gzip file ?<BR></FONT><BR>Thanks,<BR>Ron.
</P></BODY></HTML>