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设计】。

相关文章

对TensorFlow中的variables_to_restore函数详解

variables_to_restore函数,是TensorFlow为滑动平均值提供。之前,也介绍过通过使用滑动平均值可以让神经网络模型更加的健壮。我们也知道,其实在TensorFlow...

scrapy自定义pipeline类实现将采集数据保存到mongodb的方法

本文实例讲述了scrapy自定义pipeline类实现将采集数据保存到mongodb的方法。分享给大家供大家参考。具体如下: # Standard Python library im...

Python logging设置和logger解析

Python logging设置和logger解析

一、logging模块讲解 1.函数:logging.basicConfig() 参数讲解: (1)level代表高于或者等于这个值时,那么我们才会记录这条日志 (2)filename代...

对Python中画图时候的线类型详解

对Python中画图时候的线类型详解

在Python中用matplotlib画图的时候,为了区分曲线的类型,给曲线上面加一些标识或者颜色。以下是颜色和标识的汇总。 颜色(color 简写为 c): 蓝色: 'b' (blue...

Flask框架学习笔记之路由和反向路由详解【图文与实例】

Flask框架学习笔记之路由和反向路由详解【图文与实例】

本文实例讲述了Flask框架学习笔记之路由和反向路由。分享给大家供大家参考,具体如下: #-*- coding:utf-8 -*- from flask import Flask,...