您好,欢迎访问一九零五行业门户网

python实现文件夹同步

定义syndirtool类,用于同步两个文件夹的内容,从/usr/local/a文件夹到/usr/local/b文件夹,执行方法:
python代码
python syndirtool.py /usr/local/a /usr/local/b
syndirtool.py文件内容:
#!/usr/bin/python # -*- coding:utf-8 -*- import os import shutil import sys import logging class syndirtool: def __init__(self,fromdir,todir): self.fromdir = fromdir self.todir = todir def syndir(self): return self.__copydir(self.fromdir,self.todir) def __copydir(self,fromdir,todir): #防止该目录不存在,创建目录 self.__mkdir(todir) count = 0 for filename in os.listdir(fromdir): if filename.startswith('.'): continue fromfile = fromdir + os.sep + filename tofile = todir + os.sep + filename if os.path.isdir(fromfile): count += self.__copydir(fromfile,tofile) else: count += self.__copyfile(fromfile,tofile) return count def __copyfile(self,fromfile,tofile): if not os.path.exists(tofile) : shutil.copy2(fromfile,tofile) logging.info("新增%s ==> %s" % (fromfile,tofile)) return 1 fromstat = os.stat(fromfile) tostat = os.stat(tofile) if fromstat.st_ctime > tostat.st_ctime: shutil.copy2(fromfile,tofile) logging.info("更新%s ==> %s" % (fromfile,tofile)) return 1 return 0 def __mkdir(self,path): # 去除首位空格 path=path.strip() # 去除尾部 \ 符号 或者 / path=path.rstrip(os.sep) # 判断路径是否存在 isexists=os.path.exists(path) # 判断结果 if not isexists: # 如果不存在则创建目录 logging.info(path+' 目录创建成功') # 创建目录操作函数 os.makedirs(path) if __name__ == '__main__': srcdir=sys.argv[1] descdir=sys.argv[2] logging.basicconfig(filename='syndirtool.log', level=logging.info) tool = syndirtool(srcdir,descdir) count += tool.syndir()
其它类似信息

推荐信息