import zstandard as zstd
import base64
def zstd_compress_b64(data):
"""使用zstd算法对data:str压缩并base64编码"""
binary_data = data.encode('utf-8')
compressor = zstd.ZstdCompressor()
compressed_data = compressor.compress(binary_data)
base64_data = base64.b64encode(compressed_data)
return base64_data.decode('utf-8')
def zstd_decompress_b64(data):
"""使用zstd算法对data进行base64解压缩并然后解zstd压缩"""
compressed_data = base64.b64decode(data)
decompressor = zstd.ZstdDecompressor()
decompressed_data = decompressor.decompress(compressed_data)
return decompressed_data.decode('utf-8')
def tst():
org_file = "test.json"
com_file = "test_compressed.json"
dcom_file = "test_decompressed.json"
with open(org_file, 'r') as f:
org_json_str = f.read()
com_data = zstd_compress_b64(org_json_str)
with open(com_file, 'w') as f:
f.write(com_data)
dcom_data = zstd_decompress_b64(com_data)
with open(dcom_file, 'w') as f:
f.write(dcom_data)
# # 数据中有\r\n不影响
# with open("output.json","r") as f:
# tst_data_str = f.read()
# tst_dcomm_str = gzip_decompress_base64(tst_data_str)
# with open("output_handle.json","w") as f:
# f.write(tst_dcomm_str)
if __name__ == "__main__":
tst()
zstd算法压缩解压缩json - python3示例
最新推荐文章于 2024-11-12 23:15:59 发布