需求
将重要文件备份到指定目录,存档文件名称为“当前日期.zip”。
前提
1) Windows系统
2) Python 3以上版本
旗舰版


1 #!usr/bin/python 2 # -*- coding:utf-8 -*- 3 #Filename:backup_v1.py 4 5 import os 6 import time 7 8 source = 'C:\\zzSource\\' 9 target_dir = 'D:\\zzBackUp\\' 10 target = target_dir+time.strftime('%Y%m%d%H%M%S')+'.zip' 11 zip_command = "zip -qr %s %s"%(target,''.join(source)) 12 print(zip_command) 13 print('---------------') 14 if os.system(zip_command)==0: 15 print('Successful backup to %s'%(target)) 16 else: 17 print('Backup FAIILED')
说明:将目录前面加zz纯粹是为了能让目录按名称排在最后,无他意。
源目录文件:
执行命令:
目标路径文件:
打开压缩包查看:
说明备份成功。
更加方便的备份方式——批处理+Python
在进行完上面的步骤之后,笔者还是觉得这样太麻烦,就用批处理解决了。


1 C: 2 cd zzPythonTest 3 python backup_v2.py 4 pause
注:这里的第二版只是将source由字符串类型变成了list类型。即:
source = ['C:\\zzSource\\','D:\\zzSource_2\\']
保存为“MyStart.bat”。双击bat,运行结果如下:
这样就实现了自动化备份。
高级版
上面的版本还是不尽人意,主要是不能和用户交互,并且备份目录也不够合理。下面的版本对此进行改进。
流程图如下:
Python代码如下:


1 #!usr/bin/python 2 # -*- coding:utf-8 -*- 3 #Filename:backup_v3.py 4 5 import os 6 import time 7 8 source = ['C:\\zzSource\\','D:\\zzSource_2\\'] 9 target_dir = 'D:\\zzBackUp\\' 10 11 #是否有新文件要备份 12 print("是否有新的文件备份?(Y/N)") 13 str=input() 14 if 'Y'==str or 'y'==str: 15 print('请输入要备份文件的源路径') 16 filePath=input() 17 source.append(filePath) 18 print('-------新的source为: %s'%(source)) 19 else: 20 print('------source仍然为: %s'%(source)) 21 22 #如果不存在目标备份目录则创建 23 today = target_dir + time.strftime('%Y%m%d') 24 if not os.path.exists(today): 25 os.mkdir(today) 26 print('成功创建备份目录 %s'%(today)) 27 28 #得到目标备份目录 29 now = time.strftime('%H%M%S') 30 print('请输入注释:') 31 comment = input() 32 if len(comment)==0: 33 target = today + os.sep + now +'.zip' 34 else: 35 target = today + os.sep + now + '_' + comment.replace(' ','_') + '.zip' 36 37 print('-----备份target: %s'%(target)) 38 39 #执行备份命令 40 zip_command = "zip -qr %s %s"%(target,' '.join(source)) 41 print(zip_command) 42 print('================================') 43 if os.system(zip_command)==0: 44 print('Successful backup to %s'%(target)) 45 else: 46 print('Backup FAIILED')
批处理文件内容如下:


1 cd C:\zzPythonTest 2 python backup_v3.py 3 pause
每次还要找到批处理文件双击才能运行,还是不够自动化啊,于是做了以下操作:
在 D 盘建立一个bat目录,专门用来存放各种批处理命令。
将上面的文件保存为backup.bat。同时在环境变量path中添加 ;D:\bat 。
win + R 进入控制台,运行命令 backup:
查看目标备份目录:
完全符合预期。
以上是抛砖引玉,还可以根据需要继续优化。
参考文献
《Python简明教程》