实际效果:假设给定目录"/media/data/programmer/project/python" ,备份路径"/home/diegoyun/backup/“ , 则会将python目录下的文件按照全路经备份到备份路径下,形如:
/home/diegoyun/backup/yyyymmddHHMMSS/python/xxx/yyy/zzz.....
复制代码 代码如下:
importos
importshutil
importdatetime
defmainLogic():
#adddirsyouwanttocopy
backdir="I:backup"
copydirs=[]
copydirs.append("D:programmer")
copydirs.append("D:diegoyun")
print"Copyingfiles==================="
start=datetime.datetime.now()
#genadatafolderforbackup
backdir=os.path.join(backdir,start.strftime("%Y-%m-%d"))
#print"backdiris:"+backdir
kc=0
fordincopydirs:
kc=kc+copyFiles(d,backdir)
end=datetime.datetime.now()
print"Finished!==================="
print"Totalfiles:"+str(kc)
print"Elapsedtime:"+str((end-start).seconds)+"seconds"
defcopyFiles(copydir,backdir):
prefix=getPathPrefix(copydir)
#print"prefixis:"+prefix
i=0
fordirpath,dirnames,filenamesinos.walk(copydir):
fornameinfilenames:
oldpath=os.path.join(dirpath,name)
newpath=omitPrefix(dirpath,prefix)
print"backdiris:"+backdir
newpath=os.path.join(backdir,newpath)
print"newpathis:"+newpath
ifos.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
returni
defgetPathPrefix(fullpath):
#Giving/media/data/programmer/project/,gettheprefix
#/media/data/programmer/
l=fullpath.split(os.path.sep)
#printstr(l[-1]=="")
ifl[-1]=="":
tmp=l[-2]
else:
tmp=l[-1]
returnfullpath[0:len(fullpath)-len(tmp)-1]
defomitPrefix(fullpath,prefix):
#Giving/media/data/programmer/project/python/tutotial/file/test.py,
#andprefixisGiving/media/data/programmer/project/,
#returnpathaspython/tutotial/file/test.py
returnfullpath[len(prefix)+1:]
mainLogic()