python备份文件的脚本

时间:2021-05-22

实际效果:假设给定目录"/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()

声明:本页内容来源网络,仅供用户参考;我单位不保证亦不表示资料全面及准确无误,也不保证亦不表示这些资料为最新信息,如因任何原因,本网内容或者用户因倚赖本网内容造成任何损失或损害,我单位将不会负任何法律责任。如涉及版权问题,请提交至online#300.cn邮箱联系删除。

相关文章