Python的gzip的:有没有办法从字符串来解压?(Python gzip: is there a

2019-08-17 15:40发布

我读过这个SO张贴解决问题无济于事。

我想解压缩从URL来一个名为.gz文件。

url_file_handle=StringIO( gz_data )
gzip_file_handle=gzip.open(url_file_handle,"r")
decompressed_data = gzip_file_handle.read()
gzip_file_handle.close()

...但我得到类型错误:强迫为Unicode:需要字符串或缓冲区,cStringIO.StringI发现

这是怎么回事?

Traceback (most recent call last):  
  File "/opt/google/google_appengine-1.2.5/google/appengine/tools/dev_appserver.py", line 2974, in _HandleRequest
    base_env_dict=env_dict)
  File "/opt/google/google_appengine-1.2.5/google/appengine/tools/dev_appserver.py", line 411, in Dispatch
    base_env_dict=base_env_dict)
  File "/opt/google/google_appengine-1.2.5/google/appengine/tools/dev_appserver.py", line 2243, in Dispatch
    self._module_dict)
  File "/opt/google/google_appengine-1.2.5/google/appengine/tools/dev_appserver.py", line 2161, in ExecuteCGI
    reset_modules = exec_script(handler_path, cgi_path, hook)
  File "/opt/google/google_appengine-1.2.5/google/appengine/tools/dev_appserver.py", line 2057, in ExecuteOrImportScript
    exec module_code in script_module.__dict__
  File "/home/jldupont/workspace/jldupont/trunk/site/app/server/tasks/debian/repo_fetcher.py", line 36, in <module>
    main()
  File "/home/jldupont/workspace/jldupont/trunk/site/app/server/tasks/debian/repo_fetcher.py", line 30, in main
    gziph=gzip.open(fh,'r')
  File "/usr/lib/python2.5/gzip.py", line 49, in open
    return GzipFile(filename, mode, compresslevel)
  File "/usr/lib/python2.5/gzip.py", line 95, in __init__
    fileobj = self.myfileobj = __builtin__.open(filename, mode or 'rb')
TypeError: coercing to Unicode: need string or buffer, cStringIO.StringI found

Answer 1:

gzip.open是打开文件的简写,你想要的是gzip.GzipFile ,你可以通过一个FileObj文件

open(filename, mode='rb', compresslevel=9)
    #Shorthand for GzipFile(filename, mode, compresslevel).

VS

class GzipFile
   __init__(self, filename=None, mode=None, compresslevel=9, fileobj=None)
   #    At least one of fileobj and filename must be given a non-trivial value.

所以这应该为你工作

gzip_file_handle = gzip.GzipFile(fileobj=url_file_handle)


Answer 2:

如果您的数据已经在一个字符串,尝试zlib的,号称是完全GZIP兼容的:

import zlib
decompressed_data = zlib.decompress(gz_data, 16+zlib.MAX_WBITS)

了解更多: http://docs.python.org/library/zlib.html



Answer 3:

考虑使用gzip.GzipFile如果你不喜欢晦涩传递参数给zlib.decompress

当你处理urllib2.urlopen应答可以是用gzip压缩或解压缩:

import gzip
from StringIO import StringIO

# response = urllib2.urlopen(...

content_raw = response.read()
if 'gzip' in response.info().getheader('Content-Encoding'):
    content = gzip.GzipFile(fileobj=StringIO(content_raw)).read()

当你处理,可以将任gzip压缩或未压缩数据的文件:

import gzip

# some_file = open(...

try:
    content = gzip.GzipFile(fileobj=some_file).read()
except IOError:
    some_file.seek(0)
    content = some_file.read()

上面的例子是在Python 2.7



文章来源: Python gzip: is there a way to decompress from a string?
标签: python gzip