有些时候,我们需要一种危机,来激发我们自身的潜能,唤醒我们内心深处被掩藏已久的人生激情,来实现人生的最大价值。这一秒不放弃,下一秒就有希望!
实际效果:假设给定目录"/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()
本文python备份文件的脚本到此结束。做一个决定,并不难,难的是付诸行动,并且坚持到底。小编再次感谢大家对我们的支持!