Python语言技术文档

微信小程序技术文档

php语言技术文档

jsp语言技术文档

asp语言技术文档

C#/.NET语言技术文档

html5/css技术文档

javascript

点击排行

您现在的位置:首页 > 技术文档 > Python编程技巧

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

来源:中文源码网    浏览:135 次    日期:2024-05-17 08:49:00
【下载文档:  python同步两个文件夹下的内容.txt 】


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)
代码简单,但是不优雅,欢迎指正。
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持中文源码网。

相关内容