需求:
文件夹备份成ZIP文件,不能破坏原有的文件夹结构,ZIP备份文件在同父级文件夹下,命名规则:FolderName_N.zip。
分析:
1. 创建zip文件命名规则:FolderName_N.zip -》while循环
2. 创建zip文件 -》zipfile.ZipFile()
3. 遍历目录树并添加到zip文件中 -》os.wark()
难点:
步骤3中,需要对os.walk中返回的文件夹路径做特殊处理,否则写入zip文件时,会从根文件开始。(PS:解决方法是百度出来的,还未透彻理解。)
解决方法:
fpath = root.replace(folder, '')
fpath = fpath and fpath + os.sep or ''
#!/usr/bin/python3
# -*- coding: utf-8 -*-
# backupToZip.py - Copies an entire folder and its contents into a ZIP file whose filename increments.
import os
import zipfile
def zip_file(baseFolder):
folder = os.path.abspath(baseFolder)
# print(os.path.basename(folder))
# 按规则命名ZIP文件
n = 1
while True:
zipFileName = os.path.basename(folder) + "_" + str(n) + ".zip"
# print(zipFileName)
# 检查backup文件编号是否已存在,不存在跳出循环,存在继续循环
bakPath = os.path.abspath(os.path.dirname(baseFolder))
if zipFileName not in os.listdir(bakPath):
# print(zipFileName)
break
n += 1
# 创建ZIP文件
zipFile = zipfile.ZipFile(os.path.dirname(baseFolder) + '\\' + zipFileName, mode='w')
# print(os.path.dirname(baseFolder) + '\\' + zipFileName)
# 遍历文件树并添加到ZIP文件中
for root, dirs, files in os.walk(folder):
fpath = root.replace(folder, '')
fpath = fpath and fpath + os.sep or ''
for filename in files:
zipFile.write(os.path.join(root, filename), fpath + filename, compress_type=zipfile.ZIP_DEFLATED)
zipFile.close()
if __name__ == "__main__":
baseFolder = "C:\\Users\cassie.yan.su\Desktop\\test\Python Files"
zip_file(baseFolder)