Python 创建 ZIP 压缩包:从整目录到自定义文件选择
Python 创建 ZIP 压缩包:从整目录到自定义文件选择
Python 让创建 ZIP 和 TAR 压缩包变得简单,无论你需要压缩整个目录还是选择特定文件。
用 shutil.make_archive 快速打包整目录:
shutil.make_archive(output_filename, 'zip', dir_name)
为精细控制,zipfile.ZipFile 类允许指定单个文件:
ZipFile.write(filename)
步骤 1:准备环境
- 导入所需模块:
from shutil import make_archive from zipfile import ZipFile from os import path import os
- 确保源文件存在并获取绝对路径。
if path.exists("guru99.txt"): src = path.realpath("guru99.txt") - 可选:重命名现有文件匹配目标名称。
步骤 2:压缩整个目录
归档文件夹内所有内容用 make_archive:
root_dir, _ = path.split(src)
make_archive("guru99_archive", "zip", root_dir)
这在当前工作目录创建 guru99_archive.zip。
步骤 3:向新 ZIP 添加特定文件
需精细控制时 ZipFile 类更理想:
with ZipFile("testguru99.zip", "w") as newzip:
newzip.write("guru99.txt")
newzip.write("guru99.txt.bak")
with 语句在块结束时自动关闭压缩包。
步骤 4:验证结果
在操作系统文件资源管理器中打开生成的 ZIP 查看内容。Windows 下双击显示包含文件列表。
以下是典型工作流的说明性截图:







完整代码(Python 3):
import os
from shutil import make_archive
from zipfile import ZipFile
from os import path
def main():
if path.exists("guru99.txt"):
# 获取源文件绝对路径
src = path.realpath("guru99.txt")
# 可选:重命名现有文件
os.rename("career.guru99.txt", "guru99.txt")
# 归档包含文件的整个目录
root_dir, _ = path.split(src)
make_archive("guru99_archive", "zip", root_dir)
# 创建第二个 ZIP 仅含选定文件
with ZipFile("testguru99.zip", "w") as newzip:
newzip.write("guru99.txt")
newzip.write("guru99.txt.bak")
if __name__ == "__main__":
main()
总结
- 压缩整个目录:调用
shutil.make_archive('name', 'zip', root_dir)。 - 添加特定文件:在
with块中用ZipFile.write(filename)。
Python
- Python入门:安装、运行与编写第一个程序
- Python 文件 I/O:掌握文件操作、读写与管理
- Python strip() 方法完全指南:去除首尾空白与自定义字符实战
- Python str.count() 完全指南:统计字符与子串出现次数实战
- Python round() 函数详解与实战示例
- 精通 Python map() 函数:语法、示例与最佳实践
- Python timeit():精准测量代码执行时间与实战示例
- Python collections.Counter:高效计数、更新与算术运算
- Python list.count() 专家指南:语法、示例与性能解析
- Python list.index() 详解:查找元素位置的实用指南与示例
- Python C 扩展开发指南:构建高性能原生模块
- Java BufferedReader 读取文件:实战指南与示例