Python5:Script

来源:互联网 发布:2015年淘宝总交易额 编辑:程序博客网 时间:2024/06/01 14:39

1.Question & Analysis

Q:为所有重要文件穿件备份的程序
  • 需要备份的文件和目录有一个列表指定
  • 备份应该保存在主备份目录中
  • 文件备份成Zip文件
  • Zip存档的日期是当前的日期和时间
  • Windows用户应该使用Info-Zip程序

2.version1.0

#backup_version1.pyimport osimport time#the file and directionaries to be backed up are specified in a listsource = ['F:\\CV\\CV.doc']; #r防止转义#the backup must be stored in a main backup directorytarget_dir = 'F:\\backup\\';#the files are backed up into a zip file#the name of the rar archive is the current data and timetarget = target_dir + time.strftime('%Y%m%d%H%M%S')+'.rar';print (target);#use the rar command to put the files in a zip archiverar_command = "Rar a %s %s" % (target,' '.join(source))print (rar_command);#run the backupif os.system(rar_command)==0:print 'Successful backup to',targetelse:print'Backup Failed'
Windows下使用Rar命令成功验证,首先确保Windows下C:\Windows\System32目录下有Rar.exe文件。

3.version2.0

修改:创建子目录,以日期命令;创建压缩文件,以时间命名。
import osimport timesource = ['F:\\CV'];target_dir = 'F:\\Backup\\';#The current day is the name of the subdirectory in the main directorytoday = target_dir + time.strftime('%Y%m%d')#The current time is the name of the rar archivenow = time.strftime('%H%M%S');#Create the subdirectory if it isn't already thereif not os.path.exists(today):    os.mkdir(today); # make directoryprint 'Successfully created directory', today;#The name of the rar filetarget = today + os.sep + now + '.rar';rar_command = "Rar a %s %s" % (target,' '.join(source));# Run the backupif 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而非直接使用字符,会使程序具有移植性。
原创粉丝点击