Python5:Script
程序员文章站
2022-04-09 21:43:02
...
1.Question & Analysis
Q:为所有重要文件穿件备份的程序
- 需要备份的文件和目录有一个列表指定
- 备份应该保存在主备份目录中
- 文件备份成Zip文件
- Zip存档的日期是当前的日期和时间
- Windows用户应该使用Info-Zip程序
2.version1.0
Windows下使用Rar命令成功验证,首先确保Windows下C:\Windows\System32目录下有Rar.exe文件。#backup_version1.py import os import time #the file and directionaries to be backed up are specified in a list source = ['F:\\CV\\CV.doc']; #r防止转义 #the backup must be stored in a main backup directory target_dir = 'F:\\backup\\'; #the files are backed up into a zip file #the name of the rar archive is the current data and time target = target_dir + time.strftime('%Y%m%d%H%M%S')+'.rar'; print (target); #use the rar command to put the files in a zip archive rar_command = "Rar a %s %s" % (target,' '.join(source)) print (rar_command); #run the backup if os.system(rar_command)==0: print 'Successful backup to',target else: print'Backup Failed'
3.version2.0
修改:创建子目录,以日期命令;创建压缩文件,以时间命名。import os import time source = ['F:\\CV']; target_dir = 'F:\\Backup\\'; #The current day is the name of the subdirectory in the main directory today = target_dir + time.strftime('%Y%m%d') #The current time is the name of the rar archive now = time.strftime('%H%M%S'); #Create the subdirectory if it isn't already there if not os.path.exists(today): os.mkdir(today); # make directory print 'Successfully created directory', today; #The name of the rar file target = today + os.sep + now + '.rar'; rar_command = "Rar a %s %s" % (target,' '.join(source)); # Run the backup if os.system(rar_command) == 0: print 'Successful backup to', target; else: print 'Backup FAILED';
两个程序的大部分是相同的。改变的部分主要是使用os.exists函数检验在主备份目录中是否有
以当前日期作为名称的目录。如果没有,我们使用os.mkdir函数创建。
注意os.sep变量的用法——这会根据操作系统给出目录分隔符,即在Linux、Unix下它是'/',在Windows下它是'\\',而在Mac OS下它是':'。使用os.sep而非直接使用字符,会使程序具有移植性。
推荐阅读