1. Zstd
Zstandard,简称 Zstd 或 zstd,是由 Facebook 开源的一款高性能无损数据压缩算法库。
Zstd 能够提供比传统压缩算法如 gzip 更高的压缩率,同时其压缩速度也非常接近快速压缩算法如 Snappy。这意味着在很多情况下,Zstd 能够在不牺牲太多处理速度的前提下,实现更小的压缩文件大小。
官网介绍参考这里。
2. 安装库
注意 Python 的 Zstd 有两个库,一个是 zstd
,一个是 zstandard
。zstd
功能比较简陋,不推荐。我们需要安装 zstandard
:
pip install zstandard
Python zstandard 压缩/解压缩的详细介绍看这里
3. 压缩
下面将原始的 input_file
Zstd 压缩到 output_file
import zstandard as zstd
def compress(input_file: str, output_file: str):
with open(input_file, "r") as inf:
with open(output_file, "wb") as outf:
cctx = zstd.ZstdCompressor()
compressed = cctx.compress(inf.read().encode())
outf.write(compressed)
# 例如:
compress("test.txt", "test.zst")
下面是我用上面函数压缩的结果:
压缩率接近 60%
4. 解压缩
下面将 Zstd压 缩的 input_file
解压到 output_file
import zstandard as zstd
def decompress(input_file: str, output_file: str):
with open(input_file, "rb") as inf:
with open(output_file, "w") as outf:
dctx = zstd.ZstdDecompressor()
decompressed = dctx.decompress(inf.read()).decode()
outf.write(decompressed)
# 例如:
decompress("test.zst", "test-2.txt")
下面是我用上面函数解压缩的结果:
5. 参考
https://python-zstandard.readthedocs.io/en/latest/
欢迎关注本人,我是喜欢搞事的程序猿; 一起进步,一起学习;
欢迎关注知乎/CSDN:SmallerFL
也欢迎关注我的wx公众号(精选高质量文章):一个比特定乾坤