python同步两个文件夹下的内容

yipeiwu_com6年前Python基础

本文实例为大家分享了python同步两个文件夹下的内容,供大家参考,具体内容如下

import os
import shutil
import time
import logging
import filecmp
#日志文件配置
log_filename ='synchro.log'
#日志输出格式化
log_format = '%(filename)s [%(asctime)s] [%(levelname)s] %(message)s'
logging.basicConfig(format=log_format,datefmt='%Y-%m-%d %H:%M:%S %p',level=logging.DEBUG) 
#日志输出到日志文件
fileLogger = logging.getLogger('fileLogger')
fh = logging.FileHandler(log_filename)
fh.setLevel(logging.INFO)
fileLogger.addHandler(fh);
#需要同步的文件夹路径,可以使用绝对路径,也可以使用相对路径
synchroPath1 = r'/home/xxx/image1'
synchroPath2 = r'/home/xxx/image2'

#同步方法
def synchro(synchroPath1,synchroPath2):
 leftDiffList = filecmp.dircmp(synchroPath1,synchroPath2).left_only
 rightDiffList = filecmp.dircmp(synchroPath1,synchroPath2).right_only
 commondirsList =filecmp.dircmp(synchroPath1,synchroPath2).common_dirs
 for item in leftDiffList:
  copyPath = synchroPath1 + '/' + item
  pastePath = synchroPath2 + '/' + item
  if(os.path.isdir(copyPath)):
   copyDir(copyPath,pastePath)
  else :
   shutil.copy2(copyPath,pastePath)
   fileLogger.info('copy '+copyPath +" to "+pastePath)
 for item in rightDiffList:
  copyPath = synchroPath2 + '/' + item
  pastePath = synchroPath1 +'/' + item
  if(os.path.isdir(copyPath)):
   copyDir(copyPath,pastePath)
  else :
   shutil.copy2(copyPath,pastePath)
   fileLogger.info('copy '+copyPath +" to "+pastePath)
 for item in commondirsList:
  copyPath = synchroPath2 + '/' + item
  pastePath = synchroPath1 +'/' + item
  syncDir(copyPath,pastePath)
#拷贝文件夹,如果文件夹不存在创建之后直接拷贝全部,如果文件夹已存在那么就同步文件夹  
def copyDir(copyPath,pastePath):
 if(os.path.exists(pastePath)):
  synchro(copyPath,pastePath)
 else :
  os.mkdir(pastePath)
  shutil.copytree(copyPath,pastePath)
#子文件夹左右两侧文件夹都包含,就同步两侧子文件夹
def syncDir(copyPath,pastePath):
  copyDir(copyPath,pastePath)
  copyDir(pastePath,copyPath)
while(True):
 synchro(synchroPath1,synchroPath2)
 logging.debug('synchro run')
 #阻塞方法,上一步执行结束后等待五秒
 time.sleep(5)

代码简单,但是不优雅,欢迎指正。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

对pandas中时间窗函数rolling的使用详解

在建模过程中,我们常常需要需要对有时间关系的数据进行整理。比如我们想要得到某一时刻过去30分钟的销量(产量,速度,消耗量等),传统方法复杂消耗资源较多,pandas提供的rolling使...

wxPython实现绘图小例子

wxPython实现绘图小例子

本文实例为大家分享了wxPython绘图小例子的具体实现代码,供大家参考,具体内容如下 一个绘图的例子: #!/usr/bin/env python # -*- coding: ut...

计算机二级python学习教程(3) python语言基本数据类型

计算机二级python学习教程(3) python语言基本数据类型

本文继续计算机二级python教程的学习,之前已经学习过了计算机二级python学习教程(1) 、计算机二级python学习教程(2) 3.1 数字类型 数字类型:整数类型、浮点数类型、...

python简单判断序列是否为空的方法

本文实例讲述了python简单判断序列是否为空的方法。分享给大家供大家参考。具体如下: 假设有如下序列: m1 = [] m2 = () m3 = {} 判断他们是否为空的高效...

Python 实现异步调用函数的示例讲解

async_call.py #coding:utf-8 from threading import Thread def async_call(fn): def wrapper...