Python 的 zipfile 模块可创建、读取、解压 ZIP 文件。1. 创建压缩文件用 ZipFile 类写模式,write() 添加文件,支持循环添加多文件及 ZIP_DEFLATED 压缩;2. 读取信息用 namelist() 和 infolist() 查看文件名与详情;3. 解压用 extractall() 到指定目录或 extract() 单个文件;4. testzip() 检测完整性,返回 None 表示正常。注意路径与模式选择。

Python 中使用 zipfile 模块可以轻松实现文件的压缩与解压,无需依赖外部工具。它支持读取、创建和写入 ZIP 格式的归档文件,适用于日常开发中的打包、备份或传输多个文件的场景。
使用 ZipFile 类并以写模式('w')打开 ZIP 文件,然后通过 write() 方法添加文件。
示例:将一个文件压缩为 zip
import zipfile
<p>with zipfile.ZipFile('example.zip', 'w') as zipf:
zipf.write('sample.txt')</p>如果要压缩多个文件,可以循环添加:
立即学习“Python免费学习笔记(深入)”;
files_to_zip = ['file1.txt', 'file2.txt', 'image.jpg']
with zipfile.ZipFile('bundle.zip', 'w') as zipf:
for file in files_to_zip:
zipf.write(file)
建议使用压缩选项减少体积:
解压压缩包,上传到FTP空间,按正常安装织梦步骤进行安装; 安装完成以后,恢复数据库,在系统设置里指定模板文件夹,然后再更新下缓存,生成下首页、内容页及列表页就可以使用了,首页调用,有些地方需要修改一下调用ID。
183
with zipfile.ZipFile('compressed.zip', 'w',
compression=zipfile.ZIP_DEFLATED) as zipf:
zipf.write('large_file.log')
查看 ZIP 文件中包含哪些文件及其详细信息。
with zipfile.ZipFile('example.zip', 'r') as zipf:
print(zipf.namelist()) # 打印所有文件名
for info in zipf.infolist():
print(f"{info.filename}: {info.file_size} bytes")
将 ZIP 文件内容解压到指定目录。
with zipfile.ZipFile('example.zip', 'r') as zipf:
zipf.extractall('output_folder/') # 解压全部
也可以只解压某个特定文件:
with zipfile.ZipFile('example.zip', 'r') as zipf:
zipf.extract('sample.txt', 'single_output/')
使用 testzip() 方法验证压缩包完整性,返回 None 表示无损坏。
with zipfile.ZipFile('suspect.zip', 'r') as zipf:
bad_file = zipf.testzip()
if bad_file:
print(f"文件损坏: {bad_file}")
else:
print("文件正常")
基本上就这些常用操作。掌握 zipfile 模块后,处理日常压缩任务会非常方便,不复杂但容易忽略细节比如路径管理和压缩模式选择。
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号