简明python教程六----编写一个python脚本

备份程序:

#!/usr/bin/python
#Filename:backup_ver1.py

import os
import time

source = ['/home/liuxj/pythontest','/home/liuxj/shell_test']
target_dir = '/mnt/backup'

target = target_dir+time.strftime('%Y%m%d%H%M%S') +'.zip'

zip_command = "zip -qr '%s' %s" %(target,' '.join(source))

if os.system(zip_command) == 0:
    print 'Successful backup to',target
else:
    print 'Backup FAILED'

 使用加法操作符来级连字符串,把两个字符串连接在一起返回一个新的字符串。

 

优化2:使用时间作为文件名,当前日期作为目录名,存放在主备份目录中。

#!/usr/bin/python
#Filename:backup_ver2.py

import os
import time

source = ['E:\\study hard(every day)\python','E:\\Ctest']

target_dir = 'E:\\backup'

today = target_dir+time.strftime('%Y%m%d')

now=time.strftime('%H%M%S')

if not os.path.exists(today):
    os.mkdir(today)
    print 'Successfully created directory',today

target = today+os.sep+now+'.zip'

zip_command = "zip -qr '%s'%s"%(target,' '.join(source))

if os.system(zip_command) == 0:
    print 'Successful backup to',target
else:
    print 'Backup FAILED'

os.exists函数检验在主备份目录中是否有以当前目录作为名称的目录

os.mkdir:如果目录不存在,则创建目录

os.sep:根据你的操作系统给出目录分隔符,在linux、unix下它是‘/’,在windows下是‘\\’,而在Mac OS下它是‘:’。使用os.sep而非直接使用字符,会使程序移植性更好。

 

优化3:通过在zip归档名上附带一个用户提供的注释来方便地实现。

 

软件开发过程,各个环节:

1.分析(什么)

2.设计(如何)

3.编写(实施)

4.测试(测试和调试)

5.使用(实施或者开发)

6.维护(优化)

记住“软件是长出来的,而不是建造的”

posted on 2017-02-11 01:00  白宫飘红旗  阅读(245)  评论(0编辑  收藏  举报