[Python] 纯文本查看 复制代码 # coding: utf-8
from zipfile import ZipFile, ZIP_DEFLATED
from io import BytesIO
def zip_compress(txt: str):
stream = BytesIO()
# 压缩并写道 io
with ZipFile(file=stream, mode='w', compression=ZIP_DEFLATED, allowZip64=False) as zip:
zip.writestr('temp',txt)
print('压缩结果<类型 bytes> : ', stream.getvalue()) #压缩结果
#从 io中 解压缩
with ZipFile(file=stream, mode='r', compression=ZIP_DEFLATED, allowZip64=False) as zip:
result = zip.read('temp')
print('解压缩结果<类型 str> : ', result.decode()) # 解压缩结果
if __name__ == '__main__':
zip_compress('Here are zip compress as buffer demo')
文件不落地 建议用 gzip 才是正确的选择 |