linesky 发表于 2010-12-22 18:45

奋战五小时,增量备份Python实现

一直想搞一搞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)
页: [1]
查看完整版本: 奋战五小时,增量备份Python实现