Actual Effect: assume that the directory "/Media/data/Programmer/project/Python" is specified, and the backup path "/home/diegoyun/backup/" is used. the file under the python directory is backed up to the backup path according to the full path, as shown in the following figure:
/Home/diegoyun/backup/yyyymmddhhmmss/Python/XXX/YYY/ZZZ .....
CopyCode The Code is as follows: Import OS
Import shutil
Import datetime
Def mainlogic ():
# Add dirs you want to copy
Backdir = "I: \ backup"
Copydirs = []
Copydirs. append ("D: \ programmer ")
Copydirs. append ("D: \ diegoyun ")
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 ()