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

发布时间:2020-08-19 19:43:06 作者:迦蓝叶
来源:脚本之家 阅读:278

本文实例为大家分享了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);
#需要同步的文件夹路径,可以使用绝对路径,也可以使用相对路径
synchroPath2 = r'/home/xxx/image1'
synchroPath3 = r'/home/xxx/image2'

#同步方法
def synchro(synchroPath2,synchroPath3):
 leftDiffList = filecmp.dircmp(synchroPath2,synchroPath3).left_only
 rightDiffList = filecmp.dircmp(synchroPath2,synchroPath3).right_only
 commondirsList =filecmp.dircmp(synchroPath2,synchroPath3).common_dirs
 for item in leftDiffList:
  copyPath = synchroPath2 + '/' + item
  pastePath = synchroPath3 + '/' + 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 = synchroPath3 + '/' + 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 commondirsList:
  copyPath = synchroPath3 + '/' + item
  pastePath = synchroPath2 +'/' + 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(synchroPath2,synchroPath3)
 logging.debug('synchro run')
 #阻塞方法,上一步执行结束后等待五秒
 time.sleep(5)

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

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持亿速云。

推荐阅读:
  1. Python3实现两个Excel文件内容比对
  2. C#如何指定文件夹下面的所有内容复制到目标文件夹下面

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

python 同步文件夹 下的

上一篇:lsof命令学习

下一篇:Redis精确去重计数方法(咆哮位图)

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》