我尝试在我的文件上写入许多 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'
There isn't a way to decompress concatenated compressed streams in a single function or method call*. However, it's possible to get equivalent functionality using the tools in the zlib package.
>>> 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
- 并在其中公开流中的剩余字节未使用的数据属性。因此我们可以循环解压缩,直到整个串联流都被解压缩。
*At least, not that I could find
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)