import zipfile
import os
def zip_folder(dir_path, zip_full_name):
"""
压缩文件夹下所有子文件夹和文件
:param dirpath: 目标文件夹路径
:param zip_full_name: zip文件绝对路径
"""
with zipfile.ZipFile(zip_full_name, 'w', zipfile.ZIP_DEFLATD) as zf:
for dir_full_path, dir_names, file_names in os.walk(dir_path):
# zip压缩包内的相对路径
dir_path_inzip = dir_full_path.replace(dirpath, '')
for dir_name in dir_names:
zf.write(os.path.join(dir_full_path, dir_name), os.path.join(dir_path_inzip, dir_name))
for file_name in file_names:
zf.write(os.path.join(dir_full_path, file_name), os.path.join(dir_path_inzip, file_name))
zf.close()
if __name__ == '__name__':
in_path = u"F:\\测试\\1"
out_path = u"F:\\测试\\输出"
folder_name_list = os.listdir(in_path)
count = 0
# 遍历输入路径下所有子文件夹,分别压缩
for folder_name in folder_name_list:
count += 1
zip_file_fullname = os.path.join(out_path, folder_name + ".zip")
print("{0}、{1}".format(count, folder_name))
print(" {0}".format(zip_file_fullname))
zip_folder(os.path.join(in_path, folder_name), zip_file_fullname)
利用Python的zipfile模块批量压缩指定文件夹下子文件夹
最新推荐文章于 2024-06-08 16:42:22 发布