Actual effect: Assuming the given directory "/media/data/programmer/project/python" and the backup Path "/home/diegoyun/backup/", the files in the Python directory are backed up to the backup path by the entire path. Shaped like:
/home/diegoyun/backup/yyyymmddhhmmss/python/xxx/yyy/zzz .....
Copy Code code 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 ()