我们看一下面版本三中作出的实质性改进。我们使用raw_input函数得到用户的注释,然后通过len函数找出输入的长度以检验用户是否确实输入了什么东西。如果用户只是按了回车(比如这只是一个惯例备份,没有做什么特别的修改),那么我们就如之前那样继续操作。
然而,如果提供了注释,那么它会被附加到zip归档名,就在.zip扩展名之前。注意我们把注释中的空格替换成下划线——这是因为处理这样的文件名要容易得多。
#!/usr/bin/python#coding=utf8#filename:backup_version3.pyimport osimport time#set the file you need backupsource = ['/home/jack/python']#set the dir you store the backup filetarget_dir='/home/jack/test/'today = target_dir + time.strftime('%Y%m%d')now = time.strftime('%H%M%S')#Take a comment from the user to create the name of the zip filecomment = raw_input('Enter a comment --> ')print len(comment)if len(comment) == 0: target = today + os.sep + now + '.zip'else: target = today + os.sep + now + '_' + comment.replace(' ', '_') + '.zip'#create the subdirectory if it isn't aready thereif not os.path.exists(today): os.mkdir(today) print 'Successfully create directory',today#set zip commandzip_command="zip -qr '%s' %s" %(target, ' '.join(source))#Run the backupif os.system(zip_command) == 0: print 'Successful backup to', targetelse: print 'Backup FAILED'
输出结果:
# python backup_file.py Enter a comment --> added new examples18Successful backup to /home/jack/test/20141111/145747_added_new_examples.zip# python backup_file.py Enter a comment --> 0Successful backup to /home/jack/test/20141111/150658.zip
带备注和不带备注两种输出结果。
python-backup-file-3,首发于运维者。
这些那些,我们是多么的了然于心,却依然,没有任何办法。