Defines the SynDirTool class, which is used to synchronize the content of two folders, from the usrlocala folder to the usrlocalb folder. the execution method is: pythonSynDirTool. pyusrlocalausrlocalbSynDirTool. py file content :#! Usrbinpython #-*-coding: UTF-8-*-importos... defines the SynDirTool class, which is used to synchronize the content of two folders, from the/usr/local/a folder to the/usr/local/B folder. the execution method is as follows:
Python code
python SynDirTool.py /usr/local/a /usr/local/b
SynDirTool. py file content:
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): # Create a directory 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 ("Added % 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 the first space path = path. strip () # Remove the tail \ symbol or/path = path. rstrip (OS. sep) # determine whether the path exists isExists = OS. path. exists (path) # judgment result if not isExists: # create the directory logging.info (path + 'directory created successfully') # create the 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. logs are output to the SynDirTool. log file in the same directory of the SynDirTool. py file.
2. if the target folder already exists and the file is newer, the file in the source folder will no longer be copied