繁体   English   中英

解压缩时Python zlib模块错误?

[英]Python zlib module error when decompressing?

前几天写了一个python程序来压缩一些Html数据并插入到数据库中。 我使用 zlib 压缩它们。

html = "<html><head><title>Title</title></head><body><p>Paragraph</p></body></html>"
compressed_html = str(zlib.compress(html.encode('utf-8'))).replace('b\'', '').replace('\'', '')

然后compressed_html 变量是这样的,

x\\\\x9c\\\\xd4\\\\xbd\\\\xfbv\\\\xdb\\\\xb6\\\\xb30\\\\xfa\\\\x7f\\\\xd6\\\\xfa\\\\xde...

今天现在我试着像这样解压缩它们。

html = html.encode('utf-8')
# html is retrieved from database.
# html is like now b'x\\x9c\\xd4\\xbd\\xfbv\\xdb\\xb6\\xb30\\xfa\\x7f\\xd6\\xfa\\xde...'
decompressed = zlib.decompress(html)

这会引发错误:

回溯(最近一次调用最后一次):

文件“C:/Users/Sakith Karunasena/PycharmProjects/Twibot Repairer/main.py”,第 16 行,在

解压 = zlib.decompress(html)

zlib.error: 解压数据时出错 -3: 不正确的标头检查

要压缩它使用这个

compressed_html = zlib.compress(html.encode(), level=6)

根据此处所需的压缩比,级别可以在 -1 到 9 之间

要存储它:

with open('filename.txt','wb') as outfile:
    outfile.write(compressed_html)

阅读它

with open('filename.txt','rb') as infile:
    compressed_html = infile.read()

解压回来

decompressed_html = zlib.decompress(compressed_html).decode()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM