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 open()文件处理使用介绍
Nov 30 Python
python连接MySQL数据库实例分析
May 12 Python
Python安装第三方库的3种方法
Jun 21 Python
numpy.std() 计算矩阵标准差的方法
Jul 11 Python
Python多线程处理实例详解【单进程/多进程】
Jan 30 Python
Django model select的多种用法详解
Jul 16 Python
纯python进行矩阵的相乘运算的方法示例
Jul 17 Python
python命名空间(namespace)简单介绍
Aug 10 Python
Python三维绘图之Matplotlib库的使用方法
Sep 20 Python
Python实现排序方法常见的四种
Jul 15 Python
python3中apply函数和lambda函数的使用详解
Feb 28 Python
Python+DeOldify实现老照片上色功能
Jun 21 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中unset,array_splice删除数组中元素的区别
2014/07/28 PHP
php实现三级级联下拉框
2016/04/17 PHP
用正则xmlHttp实现的偷(转)
2007/01/22 Javascript
用ADODB.Stream转换
2007/01/22 Javascript
支持ie与FireFox的剪切板操作代码
2009/09/28 Javascript
JavaScript(js)设置默认输入焦点(focus)
2012/12/28 Javascript
有关jQuery中parent()和siblings()的小问题
2016/06/01 Javascript
jquery select2的使用心得(推荐)
2016/12/04 Javascript
vue快捷键与基础指令详解
2017/06/01 Javascript
vue组件之Alert的实现代码
2017/10/17 Javascript
详解node child_process模块学习笔记
2018/01/24 Javascript
详解刷新页面vuex数据不消失和不跳转页面的解决
2018/01/30 Javascript
vue鼠标移入添加class样式,鼠标移出去除样式(active)实现方法
2018/08/22 Javascript
详解vue使用vue-layer-mobile组件实现toast,loading效果
2018/08/31 Javascript
怎么使用javascript深度拷贝一个数组
2019/06/06 Javascript
JavaScript实现公告栏上下滚动效果
2020/03/13 Javascript
如何在现代JavaScript中编写异步任务
2021/01/31 Javascript
[51:26]DOTA2上海特级锦标赛主赛事日 - 2 胜者组第一轮#3Secret VS OG第二局
2016/03/03 DOTA
python解析html开发库pyquery使用方法
2014/02/07 Python
python PyTorch参数初始化和Finetune
2018/02/11 Python
对pandas将dataframe中某列按照条件赋值的实例讲解
2018/11/29 Python
10招!看骨灰级Pythoner玩转Python的方法
2019/04/15 Python
python画图的函数用法以及技巧
2019/06/28 Python
python读取.mat文件的数据及实例代码
2019/07/12 Python
在Python中获取操作系统的进程信息
2019/08/27 Python
python 使用elasticsearch 实现翻页的三种方式
2020/07/31 Python
python如何实现word批量转HTML
2020/09/30 Python
Python通过getattr函数获取对象的属性值
2020/10/16 Python
8款精美的CSS3表单设计(登录表单/下拉选择/按钮附演示及源码)
2013/02/04 HTML / CSS
马来西亚户外装备商店:PTT Outdoor
2019/07/13 全球购物
高中生自我评价个人范文
2013/11/09 职场文书
夫妻双方自愿离婚协议书
2014/10/24 职场文书
民事赔偿协议书
2014/11/02 职场文书
在校证明模板
2015/06/17 职场文书
大学生十八大感想
2015/08/11 职场文书
python_tkinter事件类型详情
2022/03/20 Python