我试图在文件上写很多zlib块,有没有办法我可以从文件中获取所有未压缩的内容?从下面的示例代码中,我只能获取我的第一个数据。预先感谢您的输入!
Python 3.6.8 |Anaconda, Inc.| (default, Dec 29 2018, 19:04:46)
[GCC 4.2.1 Compatible Clang 4.0.1 (tags/RELEASE_401/final)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import zlib
>>> str1 = b'my first string'
>>> str2 = b'my second string'
>>> z1 = zlib.compress(str1)
>>> z2 = zlib.compress(str2)
>>> with open('test.z', 'wb') as fh:
... fh.write(z1)
... fh.write(z2)
...
23
24
>>> p = open('test.z','rb').read()
>>> p
b'x\x9c\xcb\xadTH\xcb,*.Q(.)\xca\xccK\x07\x00.6\x05\xe6x\x9c\xcb\xadT(NM\xce\xcfKQ(.)\xca\xccK\x07\x003\xfb\x06:'
>>> zlib.decompress(p)
b'my first string'
>>> zlib.decompress(p)
b'my first string'
没有一种方法可以在单个函数或方法调用中解压缩连接的压缩流*。但是,可以使用zlib程序包中的工具来获得等效的功能。
>>> import zlib
>>> b1 = b'Here is some data'
>>> b2 = b'Here is some more data'
>>> stream = zlib.compress(b1) + zlib.compress(b2)
>>> while stream:
... dco = zlib.decompressobj()
... dec = dco.decompress(stream)
... print(dec)
... stream = dco.unused_data
...
b'Here is some data'
b'Here is some more data'
zlib.decompressobj()创建一个对象,该对象对单个压缩流进行解压缩(如zlib.decompress
),并在其unused_data属性中公开该流中的其余字节。因此,我们可以在循环中进行解压缩,直到对整个串联流进行解压缩为止。
* 至少,不是我能找到的