Import osimport shutilimport datetime ''' function: Back up the directory to another path. Actual Effect: assume that the directory "/Media/data/Programmer/project/Python" is specified, and the backup path "/home/diegoyun/backup/" is used. the Python directory is backed up to the backup path, for example,/home/diegoyun/backup/yyyymmddhhmmss/Python/XXX/YYY/ZZZ .. usage: change these two parameters. backdir: Backup destination. copydirs: folder to be backed up. '''def mainlogic (): # Add dirs you want to copy backdir = "D: \ test" Print (backdir) copydirs = [] copydirs. append ("D: \ Temp"); # copydirs. append ("d :\\ test"); print ("copying files ==== ================ ") Start = datetime. datetime. now () # Gen a data folder for backup backdir = OS. path. join (backdir, start. strftime ("% Y-% m-% d") # print ("backdir is:" + backdir) kc = 0 for D in copydirs: KC = KC + copyfiles (D, backdir) End = datetime. datetime. now () print ("finished! ======================== ") Print (" Total files: "+ STR (KC) print (" elapsed time: "+ STR (end-Start ). seconds) + "seconds") def copyfiles (copydir, backdir): prefix = getpathprefix (copydir) # print ("prefix is:" + prefix) I = 0 for dirpath, dirnames, filenames in OS. walk (copydir): For name in filenames: oldpath = OS. path. join (dirpath, name) newpath = omitprefix (dirpath, prefix) print ("backdir Is: "+ backdir) newpath = OS. Path. Join (backdir, newpath) print (" newpath is: "+ newpath) If OS. Path. exists (newpath )! = True: OS. makedirs (newpath) newpath = OS. path. join (newpath, name) print ("from:" + oldpath + "to:" + newpath) shutil. copyfile (oldpath, newpath) I = I + 1 return I def getpathprefix (fullpath): # Giving/Media/data/Programmer/project /, get the prefix #/Media/data/Programmer/L = fullpath. split (OS. path. SEP) # print (STR (L [-1] = "") if l [-1] = "": TMP = L [-2] else: TMP = L [-1] Return fullpath [0: Len (fullpath)-len (TMP)-1] def omitprefix (fullpath, prefix ): # Giving/Media/data/Programmer/project/Python/tutotial/file/test. PY, # And prefix is giving/Media/data/Programmer/project/, # return path as Python/tutotial/file/test. PY return fullpath [Len (prefix) + 1:] mainlogic ()