内容选自《Python编程快速上手 让繁琐工作自动化》 第九章 文件组织
先贴一下代码块:
import zipfile,os,re
def backupToZip(folder):
# 返回path规范化的绝对路径
folder = os.path.abspath(folder)
# 获取 path 的字节数,后面在字符串索引时使用
lenNum = len(folder) + 1
number = 1
while True:
# 生成压缩文件的名称 basename
zipFilename = os.path.basename(folder) + '_' + str(number) + '.zip'
# 如果path存在,返回True;如果path不存在,返回False
# os.path.exists(zipFilename) 为False时,not False 为真时才触发 break
# 当检测到名字存在时,number + 1
if not os.path.exists(zipFilename):
break
number = number + 1
print('Creating %s...' %(zipFilename))
# 新建一个压缩包
backupZip = zipfile.ZipFile(zipFilename,'w')
# 执行一个for循环,打印,并不断添加文件到压缩包中
for foldername,subfolders,filenames in os.walk(folder):
print('Adding files in %s...' %(foldername))
for filename in filenames:
# path 是被压缩文件的位置
path = foldername + '\\' + filename
# path2 是压缩包的位置,使用字符串索引 path 来获得
path2 = path[lenNum:]
print("Path : " + path)
print("Path2 : " + path2)
backupZip.write(path,path2,compress_type = zipfile.ZIP_DEFLATED)
backupZip.close()
print('Done.')
backupToZip('D:\\hello')
代码运行结果:


几个问题点:
将多个文件添加到压缩包
将 hello1.txt hello2.txt 添加到压缩包
backupZip.write(‘hello1.txt’,compress_type = zipfile.ZIP_DEFLATED)
backupZip.write(‘hello2.txt’,compress_type = zipfile.ZIP_DEFLATED)
将文件夹和子文件添加到压缩包
将 hello1.txt Test\hello2.txt 添加到压缩包,只用把路径一并添加
backupZip.write(‘hello1.txt’,compress_type = zipfile.ZIP_DEFLATED)
backupZip.write(‘Test\\hello2.txt’,compress_type = zipfile.ZIP_DEFLATED)
添加其它路径的文件到压缩包
将 D:\Test 文件夹下的文件 hello1.txt Test\hello2.txt 添加到压缩包,只用修改一下路径
backupZip.write(‘D:\\Test\\hello1.txt’,compress_type = zipfile.ZIP_DEFLATED)
backupZip.write(‘D:\\Test\\Test\\hello2.txt’,compress_type = zipfile.ZIP_DEFLATED)
但压缩的结果会包含文件夹 Test ,如果想要剔除,就需要使用第二个参数
backupZip.write(path,path2,compress_type = zipfile.ZIP_DEFLATED)
例如:path:D:\Test\hello1.txt ,path2: hello1.txt
使用字符串引用来获得 path2,(最开始考虑用正则表达式,但有转义符‘\’的问题)
这样我们就完成了将一个文件夹备份到一个ZIP文件,只需要在Python代码中修改想要打包的文件位置【backupToZip('D:\hello')】就可以一键命名打包。再丰富一些代码,就可以做到实时备份的功能了。
网友评论