Define the Syndirtool class, which synchronizes the contents of two folders, from the/usr/local/a folder to the/usr/local/b folder, and executes the method:
Python code
Python syndirtool.py/usr/local/a /usr/local/b
syndirtool.py File Contents:
Python code
#!/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): #防止该目录不存在, creating a directory Self.__mkdir (todir) count = 0 for filename in Os.listdir (fromdir): If Filename.starts With ('. '): 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,fro Mfile,tofile): If not os.path.exists (tofile): Shutil.copy2 (fromfile,tofile) logging.in Fo ("New%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 ("Update%s ==> %s "% (Fromfile,tofile)) return 1 return 0 def __mkdir (self,path): # Remove first space Path=path.strip () # remove tail \ Symbol or/Path=path.rstrip (OS.SEP) # to determine if the path exists isexists= Os.path.exists (PATH) # evaluates if not isexists: # Creates a directory logging.info if it does not exist (path+ ' Directory creation succeeded ') # Create directory operation function 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 ()
Note:
1, the log is output to the SynDirTool.log file in the same directory as the syndirtool.py file
2, if the destination folder already has the file, and the file is newer, the files in the source folder will no longer be copied