Python Zstd压缩解压

python 复制代码
import tarfile
from pathlib import Path
from compression.zstd import ZstdFile, CompressionParameter


def compress_folder(src_folder: str, output_file: str, level: int = 9):
    """
    将 src_folder 文件夹压缩为一个 .tar.zst 文件
    :param src_folder: 待压缩的文件夹路径
    :param output_file: 输出的压缩文件路径,例如 'archive.tar.zst'
    :param level: 压缩级别 (1-22,默认22为最高,速度越慢)
    """
    src_path = Path(src_folder)
    if not src_path.is_dir():
        raise NotADirectoryError(f"{src_folder} 不是一个有效的文件夹")

    # 打开 zstd 压缩文件(以二进制写模式),并指定压缩级别
    with ZstdFile(output_file, mode="wb",
                  options={CompressionParameter.compression_level: level}) as zf:
        # 在 zstd 压缩流之上再包一层 tar 归档,实现"打包+压缩"
        with tarfile.open(fileobj=zf, mode="w|") as tar:
            tar.add(src_path, arcname=src_path.name)

    print(f"压缩完成: {output_file}")


def decompress_folder(archive_file: str, dest_folder: str = "."):
    """
    解压 .tar.zst 文件到指定目录
    :param archive_file: 压缩文件路径,例如 'archive.tar.zst'
    :param dest_folder: 解压目标目录,默认当前目录
    """
    Path(dest_folder).mkdir(parents=True, exist_ok=True)

    with ZstdFile(archive_file, mode="rb") as zf:
        with tarfile.open(fileobj=zf, mode="r|") as tar:
            tar.extractall(path=dest_folder)  # Python 3.14 默认使用安全过滤器 filter="data"

    print(f"解压完成,文件已还原到: {dest_folder}")


if __name__ == "__main__":
    # compress_folder("C:/Users/zhoull/Downloads/ebook", "C:/Users/zhoull/Downloads/ebook.tar.zst", level=9)
    decompress_folder("C:/Users/zhoull/Downloads/ebook.tar.zst", "D:/output_folder")
相关推荐
oooost5 分钟前
Jupyter Notebook 常用快捷键速查
ide·python·jupyter
阿钱真强道19 分钟前
30 嵌入式操作系统 | 上位机界面:Flask 网页显示 + 控制闭环
后端·python·flask
ysu_031420 分钟前
Docker-Desktop-WSL2实战指南-Windows从安装配置到项目容器化
windows·python·docker·容器·composer·dockerfile·wsl2
郝学胜-神的一滴1 小时前
AI 编程智能体 02:AI智能体到底是什么
开发语言·人工智能·python·程序人生·pycharm
Guarding and trust1 小时前
python系列之多线程编程
python
梅雅达编程笔记1 小时前
03_网页表格数据抓取
爬虫·python·beautifulsoup·pandas·数据采集
迅猛龙办公室1 小时前
Python实现求两个数字之和
java·开发语言·python
企业数字化笔记1 小时前
视频成片怎么稳定导出?编码选择、GPU/CPU降级与媒体交付验收
java·python·ffmpeg
szial2 小时前
网络爬虫与 CDP 实战(一):网页数据到底在哪?从 HTTP 到分页采集
网络·爬虫·python·网络爬虫
DanCheng-studio2 小时前
智能科学与技术毕设易上手题目建议
python·毕业设计·毕设