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)

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

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值