编写Python脚本来备份文件

问题:需要写一个程序来备份所有重要的文件。

在编写程序之前还是需要弄清楚需求是什么,才能更好的设计程序。

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代替可以使得程序可移植以及跨平台。




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值