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")
相关推荐
YCOSA20252 小时前
系统工具使用检测.exe (仅供娱乐)
python·microsoft
2601_962295332 小时前
如何python实现网页的自动化
python·selenium·beautifulsoup·requests·网页自动化
ofoxcoding2 小时前
GPT Image 2.5 API 实战:Python 调用实现图片生成与编辑
人工智能·python·gpt·ai
张小姐的猫2 小时前
【AI大模型接入SDK】 —— Gemini接入封装
android·数据结构·数据库·c++·人工智能·python
Elastic 中国社区官方博客3 小时前
Elasticsearch Python DSL 客户端开发
大数据·数据库·python·elasticsearch·搜索引擎·全文检索
计算机编程-吉哥4 小时前
脑肿瘤MRI智能识别系统:基于深度学习的像素级脑肿瘤语义分割平台【计算机毕业设计选题推荐】
人工智能·python·深度学习·算法·毕业设计·课程设计·大数据毕业设计选题推荐
小木_.4 小时前
Python 离线识别滑块缺口距离,项目推荐
开发语言·python·滑块识别·人机验证·滑块缺口·缺口识别
Cenxi4 小时前
Python字符串方法练习手册
人工智能·python
liliangcsdn4 小时前
因子权重矩阵处理-因子权重收缩Shrinkage算法的探索
开发语言·python·机器学习
用户8356290780514 小时前
使用 Python 在 Excel 中添加和编辑形状
后端·python