免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 2319 | 回复: 0
打印 上一主题 下一主题

奋战五小时,增量备份Python实现 [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2010-12-22 18:45 |只看该作者 |倒序浏览
一直想搞一搞Python,却一直没得空闲,这不,正好周六,博星也在,于是从头开始,先是看python的手册,一个简明手册看了两个小时,然后写了下 面的脚本,实现了文件的增量备份……回头看起来,其实并不复杂,除了一个递归,只有語法了,而后者让我们花费了大量的时间。python在服务器端的一些操作还是很方便的,感觉这是一门很讨人喜欢的语言,代码如下:


#!/usr/bin/python
#-*-coding:utf-8-*-
#Filename: auto_bak.py
#Author: zz
import os
import sys

def get_dir(path):
    print path, '\n'
    return os.listdir(path)

def bak_file(path,path_bak):

    list = os.listdir(path)
    for l in list:
        file_path     = os.path.join(path, l)
        file_path_bak = os.path.join(path_bak, l)
        print file_path
        #如果文件路径为目录
        if os.path.isdir(file_path):

            #如果在备份目录中文件夹不存在则创建
            if not os.path.isdir(file_path_bak):

                create_com = '''mkdir -p '%s' ''' \
                             % (file_path_bak)

                if os.system(create_com) == 0:
                    print create_com
                else:
                    print 'create folder failure!'
                    os._exit(0)

            bak_file(file_path, file_path_bak)
        else:
            #如果文件已经存在,则比较文件修改时间
            if os.path.isfile(file_path_bak):

                stat_bak    = os.stat(file_path_bak)
                stat_source = os.stat(file_path)

                #判断文件修改时间
                if stat_source.st_mtime <= stat_bak.st_mtime:
                    continue

            cp_com  = '''cp '%s' '%s' ''' \
                      % (file_path, file_path_bak)

            if os.system(cp_com) == 0:
                print cp_com
            else:
                print 'create folder failure!'
                os._exit(0)

#要备份的文件目录
path     = '/home/zyf/appspot/auto_bak/a'
#备份文件目录
path_bak = '/home/zyf/appspot/auto_bak/bak'
#开始备份
bak_file(path, path_bak)
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP