问题:需要写一个程序来备份所有重要的文件。
在编写程序之前还是需要弄清楚需求是什么,才能更好的设计程序。
1.需要备份的文件和目录需要在一个列表中指定。
2.备份需要备份到一个文件夹中。
3.备份的文件需要被压缩成为zip文件。
4.zip文件的名字应该是当前的日期和时间,同时还能让用户在后面附加注释。
Talk is cheap, show me the code:
#!/usr/bin/python
import os,time
#the files and dirs to be backed up are specifiedin a list
source = ['/home/nlg/C++','/home/nlg/Java']
#the backup must be stored up into a zip file
target_dir = '/home/nlg/backup'
if not os.path.exists(target_dir):
os.mkdir(target_dir)
print('Create dir ' + target_dir + 'successfully')
today = target_dir + os.sep + time.strftime('%Y%m%d')
now = time.strftime('%H%M%S')
comment = raw_input("Enter a comment -->")
if len(comment) == 0:
target = today + os.sep + now + '.zip'
else:
target = today + os.sep + now + '_' + comment.replace(' ','_')+'.zip'
if not os.path.exists(today):
os.mkdir(today)
print('Create dir ' + target + ' successfully')
zip_cmd = "zip -rq '%s' %s" % (target,' '.join(source) )
if os.system( zip_cmd ) == 0:
print 'Successful backup to ',target
else:
print 'Backup Failed'
运行结果:
对程序进行简单的分析:
1.zip压缩命令选项"-q"选项被用于表示自拍命令应该安静(quietly)的被执行。"-r"选项表示对于目录文件递归的执行。
2.os.system()执行系统命令。如果执行成功返回0;否则返回错误码。
3.os.sep:这个变量表示目录分隔符,根据操作系统的不同,在linux或者Unix中是"/";在windows中是"\\";在MacOS中是":"。不直接使用这些符号,而是用os.sep代替可以使得程序可移植以及跨平台。