涉及知识点:
- 遍历目录树:os.walk()
- 压缩目录中的文件:zipfile
1.压缩指定目录下的所有文件和目录
import zipfile, os
dir_path = 'D:\\workspace\\demo_dir\\zipfile_test'
output_path = 'D:\\workspace\\demo_dir\\a.zip'
def zipDir(dirpath, outFullName):
'''
压缩指定目录中的所有文件和子目录
:param dirpath: 目标文件夹路径
:param outFullName: 压缩文件保存路径+XXXX.zip
:return: 无
'''
# 创建zip对象,
zip = zipfile.ZipFile(outFullName, 'w', zipfile.ZIP_DEFLATED)
# 遍历目录树,path:当前遍历的目录,dirnames:当前遍历目录中的子目录列表,也是后续继续遍历的目录
# filenames:当前目录下的所有文件名列表
for path, dirnames, filenames in os.walk(dirpath):
# fpath相当于zip中的根目录
fpath = path.replace(dir_path, '')
# 确保空目录也能被压缩
if len(filenames) == 0:
zip.write(path, fpath)
for filename in filenames:
# 参数:目标文件路径和zip中的全路径
zip.write(os.path.join(path, filename), os.path.join(fpath, filename))
zip.close()
zipDir(dir_path, output_path)
参考:https://www.cnblogs.com/Lclog/p/10680638.html