Python怎样自动压缩和解压zip压缩文件
配套视频:
代码实现:
导入所需要的包
import os
import zipfile
压缩文件夹
def zip_file(dir_path):
with zipfile.ZipFile(dir_path + ".zip", "w", zipfile.ZIP_DEFLATED) as zfile:
for iter_dir_path, dirs, files in os.walk(dir_path):
for file in files:
fpath = os.path.join(iter_dir_path, file)
zfile.write(fpath)
解压.zip文件:
def unzip_file(zip_file, target_dir):
with zipfile.ZipFile(zip_file, "r") as zfile:
for file in zfile.namelist():
zfile.extract(file, target_dir)
测试方法:
zip_file("数据文件夹")
unzip_file("数据文件夹.zip", "解压文件夹")
代码地址:http://dwz.win/ZvG
评论