当前位置:  开发笔记 > 编程语言 > 正文

Python gzip:有没有办法从字符串解压缩?

如何解决《Pythongzip:有没有办法从字符串解压缩?》经验,为你挑选了2个好方法。

我已经阅读了这篇关于这个问题的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()

...但我得到TypeError:强制转换为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 
    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

小智.. 46

如果您的数据已经在字符串中,请尝试zlib,它声称完全兼容gzip:

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

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



1> 小智..:

如果您的数据已经在字符串中,请尝试zlib,它声称完全兼容gzip:

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

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


这也是我一开始就遇到的.但它很快证明它不起作用:"zlib.error:解压缩数据时出错-3:错误的标题检查"
添加参数使调用看起来像`decompressed_data = zlib.decompress(gz_data,16 + zlib.MAX_WBITS)`,对我来说就像一个魅力.感谢http://stackoverflow.com/a/2695575/3635816

2> Jehiah..:

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)

推荐阅读
mobiledu2402851377
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有