欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

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

程序员文章站 2023-01-04 08:21:08
本文实例为大家分享了python同步两个文件夹下的内容,供大家参考,具体内容如下 import os import shutil import time i...

本文实例为大家分享了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)

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

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