Python实现定期检查源目录与备份目录的差异并进行备份功能示例


Posted in Python onFebruary 27, 2019

本文实例讲述了Python实现定期检查源目录与备份目录的差异并进行备份功能。分享给大家供大家参考,具体如下:

在项目中,经常要更新文件,在更新之前首先要备份源文件,所以就用到了这个脚本(来自于Python自动化运维这本书),总共有以下几个步骤:

1. 获取要进行比较的两个目录,进行差异比较,把源目录特有的文件或目录、以及和备份目录不同的文件或目录保存到列表中,并且判断目录下面是否还有目录,递归进行保存这些差异文件。
2. 将差异文件列表中文件或目录的路径换成对应的备份路径,进行判断,如果备份路径不存在,就创建目录。
3. 继续对比源目录和新创建的备份目录中的差异文件,把源路径换成备份目录的路径。
4. 然后遍历复制源目录文件到备份目录。

以下是具体的实现代码:

#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os, sys
import filecmp
import re
import shutil
holderlist = []
##对应第一个步骤
def compare_me(dir1, dir2):
  dircomp = filecmp.dircmp(dir1, dir2)
  only_in_one = dircomp.left_only
  diff_in_one = dircomp.diff_files
  dirpath = os.path.abspath(dir1)
  [ holderlist.append(os.path.abspath(os.path.join(dir1, x))) for x in only_in_one ]
  [ holderlist.append(os.path.abspath(os.path.join(dir1, x))) for x in diff_in_one ]
  if len(dircomp.common_dirs) > 0:
    for item in dircomp.common_dirs:
      compare_me(os.path.abspath(os.path.join(dir1, item)), os.path.abspath(os.path.join(dir2, item)))
  return holderlist
##对应第二个步骤
def main():
  if len(sys.argv) > 2:
    dir1 = sys.argv[1]
    dir2 = sys.argv[2]
  else:
    print "Usage: ", sys.argv[0], "datadir backupdir"
    sys.exit()
  source_files = compare_me(dir1, dir2)
  dir1 = os.path.abspath(dir1)
  if not dir2.endswith('/'):
    dir2 = dir2 + '/'
  dir2 = os.path.abspath(dir2)
  destination_files = []
  createdir_bool = False
  for item in source_files:
    destination_dir = re.sub(dir1, dir2, item)
    destination_files.append(destination_dir)
    if os.path.isdir(item):
      if not os.path.exists(destination_dir):
        os.makedirs(destination_dir)
        createdir_bool = True
   ##对应第三个步骤
  if createdir_bool:
    destination_files = []
    source_files = []
    source_files = compare_me(dir1, dir2)
    for item in source_files:
      destination_dir = re.sub(dir1, dir2, item)
      destination_files.append(destination_dir)
  ##对应第四个步骤
  print "update item: "
  print source_files
  copy_pair = zip(source_files, destination_files)
  print "copy_pair is %s" % copy_pair
  for item in copy_pair:
    print "item is %s, %s" % (item[0], item[1])
    if os.path.isfile(item[0]):
      shutil.copyfile(item[0], item[1])
if __name__ == '__main__':
  main()

最后根据需要,可以设定一个定时检查,进行自动同步源目录和备份目录,让其保持一致性。

Python 相关文章推荐
python使用循环实现批量创建文件夹示例
Mar 25 Python
python中__call__方法示例分析
Oct 11 Python
Windows下为Python安装Matplotlib模块
Nov 06 Python
Python3安装Pymongo详细步骤
May 26 Python
Python实现求两个csv文件交集的方法
Sep 06 Python
python将字符串list写入excel和txt的实例
Jul 20 Python
python实现最速下降法
Mar 24 Python
keras绘制acc和loss曲线图实例
Jun 15 Python
python 识别登录验证码图片功能的实现代码(完整代码)
Jul 03 Python
Numpy实现卷积神经网络(CNN)的示例
Oct 09 Python
Python hashlib模块的使用示例
Oct 09 Python
Python基础之Socket通信原理
Apr 22 Python
详解Django-restframework 之频率源码分析
Feb 27 #Python
Python的UTC时间转换讲解
Feb 26 #Python
Python逐行读取文件中内容的简单方法
Feb 26 #Python
Python计算时间间隔(精确到微妙)的代码实例
Feb 26 #Python
python3编写ThinkPHP命令执行Getshell的方法
Feb 26 #Python
初探利用Python进行图文识别(OCR)
Feb 26 #Python
Python编写合并字典并实现敏感目录的小脚本
Feb 26 #Python
You might like
php实现的单一入口应用程序实例分析
2015/09/23 PHP
Symfony2使用Doctrine进行数据库查询方法实例总结
2016/03/18 PHP
PHP常见错误提示含义解释(实用!值得收藏)
2016/04/25 PHP
Code:findPosX 和 findPosY
2006/12/20 Javascript
Jquery进度条插件 Progress Bar小问题解决
2011/07/12 Javascript
jQuery 一个图片切换的插件
2011/10/09 Javascript
密码强度检测效果实现原理与代码
2013/01/04 Javascript
Jquery取得iframe下内容的方法
2013/11/18 Javascript
jQuery插件datepicker 日期连续选择
2015/06/12 Javascript
JS中offset和匀速动画详解
2018/02/06 Javascript
Vue.js 实现数据展示全部和收起功能
2018/09/05 Javascript
使用pm2部署node生产环境的方法步骤
2019/03/09 Javascript
基于vue-cli搭建多模块且各模块独立打包的项目
2019/06/12 Javascript
Layui给switch添加响应事件的例子
2019/09/03 Javascript
jquery实现简易验证插件封装
2020/09/13 jQuery
在Vue中使用Select选择器拼接label的操作
2020/10/22 Javascript
[59:42]Secret vs Alliacne 2019国际邀请赛小组赛 BO2 第一场 8.15
2019/08/17 DOTA
深入理解Python装饰器
2016/07/27 Python
python with提前退出遇到的坑与解决方案
2018/01/05 Python
Python基于TCP实现会聊天的小机器人功能示例
2018/04/09 Python
下载python中Crypto库报错:ModuleNotFoundError: No module named ‘Crypto’的解决
2018/04/23 Python
python 返回列表中某个值的索引方法
2018/11/07 Python
Django异步任务线程池实现原理
2019/12/17 Python
css3 实现元素弧线运动的示例代码
2020/04/24 HTML / CSS
使用phonegap查找联系人的实现方法
2017/03/31 HTML / CSS
英国安全产品购物网站:The Safe Shop
2017/03/20 全球购物
维多利亚的秘密官方旗舰店:VICTORIA’S SECRET
2018/04/02 全球购物
次世代生活态度:Hypebeast
2018/07/05 全球购物
美团网旗下网上订餐平台:美团外卖
2020/03/05 全球购物
财会自我鉴定范文
2013/12/27 职场文书
土木工程专业推荐信
2014/02/19 职场文书
空中乘务员岗位职责
2014/03/08 职场文书
小学生竞选班长演讲稿
2014/04/24 职场文书
爱我中华演讲稿
2014/05/20 职场文书
中学学校门卫岗位职责
2014/08/15 职场文书
公司规章制度范本
2015/08/03 职场文书