用 Python 解压缩缓冲区? [英] Unzip buffer with Python?

查看:41
本文介绍了用 Python 解压缩缓冲区?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个从库调用中读取的字节缓冲区,我想解压缩单个文本文件的内容.

我尝试使用 zlib,但出现此错误:

<预><代码>>>>导入 zlib>>>zlib.decompress(缓冲)错误:解压缩数据时出错 -3:不正确的标头检查

但是使用 ZipFile 它可以工作,但我必须使用一个临时文件:

导入压缩文件f = open('foo.zip', 'wb')f.写(缓冲区)f.close()z = ZipFile('foo.zip')z.extractall()z.close()with open('foo.txt', 'r') as f:uncompressed_buffer = f.read()

是否可以使用 zlib 以及如何避免使用临时文件?

解决方案

是否可以使用zlib

不,zlib 不是为处理 ZIP 文件而设计的.

<块引用>

以及如何避免使用临时文件?

使用io.BytesIO:

导入压缩文件导入 io缓冲区 = b'PK\x03\x04\n\x00\x00\x00\x00\x00\n\\\x88Gzzo\xed\x03\x00\x00\x00\x03\x00\x00\x00\x07\x00\x1c\x00foo.txtUT\t\x00\x03$\x14gV(\x14gVux\x0b\x00\x01\x041\x04\x00\x00\x041\x04\x00\x00hi\nPK\x01\x02\x1en\x00\x00\x00\x00\x00\n\\\x88Gzzo\xed\x03\x00\x00\x00\x03\x00\x00\x00\x07\x00\x18\x00\x00\x00\x00\x00\x01\x00\x00\x00\xb4\x81\x00\x00\x00\x00foo.txtUT\x05\x00\x03$\x14gVux\x0b\x00\x01\x041\x04\x00\x100\x4\x00\x00PK\x05\x06\x00\x00\x00\x00\x01\x00\x01\x00M\x00\x00\x00D\x00\x00\x00\x00\x00'z = zipfile.ZipFile(io.BytesIO(buffer))# 以下三行是备选.使用其中之一#根据你的需要:foo = z.read('foo.txt') # 从foo.txt"读取数据foo2 = z.read(z.infolist()[0]) # 从第一个文件读取数据z.extractall() # 复制 foo.txt 到文件系统z.close()打印 foo打印 foo2

I have a buffer of bytes read from a library call and I would like to unzip the content which is a single text file.

I tried with zlib, but I get this error:

>>> import zlib
>>> zlib.decompress(buffer)
error: Error -3 while decompressing data: incorrect header check

However with ZipFile it works, but I have to use a temporary file:

import zipfile
f = open('foo.zip', 'wb')
f.write(buffer)
f.close()
z = ZipFile('foo.zip')
z.extractall()
z.close()
with open('foo.txt', 'r') as f:
    uncompressed_buffer = f.read()

Is it possible to use zlib and how can I avoid using a temporary file?

解决方案

Is it possible to use zlib

No, zlib is not designed to operate on ZIP files.

and how can I avoid using a temporary file?

Use io.BytesIO:

import zipfile
import io

buffer = b'PK\x03\x04\n\x00\x00\x00\x00\x00\n\\\x88Gzzo\xed\x03\x00\x00\x00\x03\x00\x00\x00\x07\x00\x1c\x00foo.txtUT\t\x00\x03$\x14gV(\x14gVux\x0b\x00\x01\x041\x04\x00\x00\x041\x04\x00\x00hi\nPK\x01\x02\x1e\x03\n\x00\x00\x00\x00\x00\n\\\x88Gzzo\xed\x03\x00\x00\x00\x03\x00\x00\x00\x07\x00\x18\x00\x00\x00\x00\x00\x01\x00\x00\x00\xb4\x81\x00\x00\x00\x00foo.txtUT\x05\x00\x03$\x14gVux\x0b\x00\x01\x041\x04\x00\x00\x041\x04\x00\x00PK\x05\x06\x00\x00\x00\x00\x01\x00\x01\x00M\x00\x00\x00D\x00\x00\x00\x00\x00'

z = zipfile.ZipFile(io.BytesIO(buffer))

# The following three lines are alternatives. Use one of them
# according to your need:
foo = z.read('foo.txt')        # Reads the data from "foo.txt"
foo2 = z.read(z.infolist()[0]) # Reads the data from the first file
z.extractall()                 # Copies foo.txt to the filesystem

z.close()


print foo
print foo2

这篇关于用 Python 解压缩缓冲区?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆