unix/windows下编写一个python脚本(文件备份)--python学习(4)

来源:互联网 发布:单片机编程入门教程 编辑:程序博客网 时间:2024/06/06 05:33

经过之前的学习,我们来学习将这些知识变成有用的程序。

首先我们来提出一个需求:为重要的文件来创建一个备份

编写程序解决问题都要首先来分析问题:1.我们准备如何确定备份文件;2.备份在哪里?3.以何种方式保存。

那么我们来针对问题采用专门的解决办法:

1.需要backup的文件和目录由一个列表指定。

2.backup应该保存灾主备份目录中。

3.文件backup的格式为zip文件哦。

4.backupfiles的名字保存为当前的日期和时间。

5.使用的zip命令为标准命令,unix系统自带。windows可以使用info-zip程序。

#!/usr/bin/python# Filename: backup_ver1.pyimport osimport time# 1. The files and directories to be backed up are specified in a list.source = ['/home/swaroop/byte', '/home/swaroop/bin']# If you are using Windows, use source = [r'C:\Documents', r'D:\Work'] or something like that# 2. The backup must be stored in a main backup directorytarget_dir = '/mnt/e/backup/' # Remember to change this to what you will be using# 3. The files are backed up into a zip file.# 4. The name of the zip archive is the current date and timetarget = target_dir + time.strftime('%Y%m%d%H%M%S') + '.zip'# 5. We use the zip command (in Unix/Linux) to put the files in a zip archivezip_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 文件名     后运行程序

我们得到如下结果:

sh: 1: zip-qr/mnt/e/backup/20170806212202.zip/home/swaroop/byte/home/swaroop/bin: not foundBackup FAILED
因为并没有这个目录,所以备份失败。

在这里我们使用了os和time模块(这两个模块会在下边介绍)。然后我们在下边的source语句中指定需要备份的文件和目录。

目标目录是我们想要存backup file的地方,此处用target_dir指定。

zip文件的名称是目前的日期和时间,使用timestrftime()函数获得

time.strftime函数需要我们在上面的程序中使用那种定制(定制是什么我也有点不清楚,不过应该就是那种特定的百分比和字母的组合符号)

%Y会被无世纪的年份代替。%m会被01到12的一个十进制月份代替,其他依次类推。

这些好像灾参考手册里有,注意:这些定制与print语句的定制类似,但不完全相同。

然后我们创建zip——command字符串,这个字符串并不能执行,需要我们来使用os.system函数执行它

最后,使用os.system函数运行命令,如果命令成功,返回0。否则报错。

今天的python学习到此结束,接下来我会对os模块,time模块的一些命令进行整理。


原创粉丝点击