【问题标题】:Decode gzip compressed and base64 encoded data to a readable format将 gzip 压缩和 base64 编码数据解码为可读格式
【发布时间】:2015-02-21 03:23:10
【问题描述】:

尝试将 gzip 压缩和 base64 编码数据解码为 Python3.4 中的可读格式。

import base64
import zlib

original_data = '...jU2X0NCQ19TSEEAAAABAAA='     #Data cut short.

decoded64 = base64.b64decode(original_data)      #format:b'\x16xe\x94...\xae\x9a\...'
final_decoded = zlib.decompress(decoded64)
print(final_decoded)

得到:“准备解压缩数据时出现错误 -2:流状态不一致。”不知道我做错了什么。

【问题讨论】:

  • original_data 来自哪里?你确定它是有效的。可以用其他方式解压吗?

标签: python python-3.x gzip zlib


【解决方案1】:

zlib成功解压之前压缩过的数据:

>>> data = b'data'
>>> import zlib
>>> compressed = zlib.compress(data)
>>> import base64
>>> original_data = base64.b64encode(compressed).decode()
>>> zlib.decompress(base64.b64decode(original_data))
b'data'

zlib 解压失败(使用默认设置)gzip 数据:

>>> import gzip
>>> gzipped_data = base64.b64encode(gzip.compress(data)).decode()
>>> gzipped_data != original_data
True
>>> print(zlib.decompress(base64.b64decode(gzipped_data)))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
zlib.error: Error -3 while decompressing data: incorrect header check
>>> gzip.decompress(base64.b64decode(gzipped_data))
b'data'

【讨论】:

    【解决方案2】:

    我遇到了同样的问题,用这种方法解决了:

    from zipfile import ZipFile
    from tempfile import SpooledTemporaryFile
    import base64
    decoded_base64 = base64.b64decode(base64_zip)
    with SpooledTemporaryFile() as tmp:
        tmp.write(decoded_base64)
        archive = ZipFile(tmp, 'r')
        for file in archive.filelist:
            content = archive.read(file.filename)
            print("The file %s have the content %s" % (file.filename, content))
    

    使用这个你的代码不会写文件,我测试过。 非常有用,因为您可以轻松读取 zip 文件中的文件,例如以前由 rest 接收的文件。

    【讨论】:

      猜你喜欢
      • 2022-07-29
      • 2021-11-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-12-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多