Python gzip 拒绝读取未压缩的文件

标签 python gzip

我似乎记得 Python gzip 模块以前允许您透明地读取非 gzip 文件。这真的很有用,因为它允许读取输入文件,无论它是否被 gzip 压缩。您根本不必担心。

现在,我得到一个 IOError 异常(在 Python 2.7.5 中):

   Traceback (most recent call last):
  File "tst.py", line 14, in <module>
    rec = fd.readline()
  File "/sw/lib/python2.7/gzip.py", line 455, in readline
    c = self.read(readsize)
  File "/sw/lib/python2.7/gzip.py", line 261, in read
    self._read(readsize)
  File "/sw/lib/python2.7/gzip.py", line 296, in _read
    self._read_gzip_header()
  File "/sw/lib/python2.7/gzip.py", line 190, in _read_gzip_header
    raise IOError, 'Not a gzipped file'
IOError: Not a gzipped file

如果有人有妙招,我想听听。是的,我知道如何捕获异常,但我发现先读取一行,然后关闭文件并再次打开它相当笨拙。

最佳答案

最好的解决方案是使用类似 https://github.com/ahupp/python-magic 的东西与 libmagic。您根本无法避免至少读取 header 来识别文件(除非您隐含地信任文件扩展名)

如果您感觉简朴,识别 gzip(1) 文件的神奇数字是前两个字节 0x1f 0x8b。

In [1]: f = open('foo.html.gz')
In [2]: print `f.read(2)`
'\x1f\x8b'

gzip.open 只是 GzipFile 的包装器,你可以有这样一个函数,它只根据源是什么返回正确的对象类型,而不必打开文件两次:

#!/usr/bin/python

import gzip

def opener(filename):
    f = open(filename,'rb')
    if (f.read(2) == '\x1f\x8b'):
        f.seek(0)
        return gzip.GzipFile(fileobj=f)
    else:
        f.seek(0)
        return f

关于Python gzip 拒绝读取未压缩的文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16813267/

相关文章:

Groovy HTTPBuilder : Getting the entity content from a GZIPed Chunked response

apache - Gzip 压缩不适用于 HTTPS

c# - 如何使Unity中的C#与Python通信

python - Matplotlib 透明线上方的透明点

python - 如何使用 Python 获取重定向的 URL

python - 如何远程控制 Bugzilla(首选 Python)

python - 访问保存在 .txt 文件中的文件路径。 (Python)

http - Varnish 不 gzip html 页面

angular - 设置 IIS10 以提供预压缩文件

python - zlib.error : Error -3 while decompressing: incorrect header check