一个简单的python备份程序

最近刚开始自学python,尝试利用python+shell做了一个简易的备份程序。

需求:我有个目录存放有需要备份的资料,我想要将他们以zip压缩文件的形式备份至U盘上的一个备份文件夹里。在备份时,只备份新的文件或者是在前一次备份过后修改过的文件,同时剔除Mac OS系统上的.DS_Store和Icon\r文件。

附上代码:

#!/usr/bin/python
# Filename: backup1webroot.py
import os,os.path,datetime
target_dir="/Volumes/FRED'S/htdocs_backup/"
source_dir='/Applications/MAMP/htdocs/'
rootlist=os.listdir(source_dir)
for webroot in rootlist:
    if webroot == ".DS_Store" or webroot == "Icon\r":
        continue
    l =  os.listdir(source_dir+webroot)
    l.sort(key=lambda fn: os.path.getmtime(source_dir+webroot+'/'+fn) if not os.path.isdir(source_dir+webroot+'/'+fn) else 0)
    d=datetime.datetime.fromtimestamp(os.path.getmtime(source_dir+webroot+'/'+l[-1]))
    t=os.path.getmtime(source_dir+webroot+'/'+l[-1])
    if (not os.path.isfile(target_dir+webroot+'.zip')) or (os.path.getmtime(target_dir+webroot+'.zip')<t):
        target = target_dir + webroot + '.zip'
        source = source_dir + webroot
        zip_command = 'zip -oqr "%s" "%s"'%(target,source)
        if os.system(zip_command) == 0:
            print webroot,'Successfully backup to',target
        else:
            print webroot,'backup FAILED.'


这样就实现了一个简易的备份文件,今后在学习更多内容后会进一步完善。

posted @ 2013-05-25 16:25  索尔斯克亚  阅读(337)  评论(0)    收藏  举报