python 拷贝特定后缀名文件,并保留原始目录结构的实例
如下所示:
#!/usr/bin/python # -*- coding: UTF-8 -*- import os import shutil def cp_tree_ext(exts,src,dest): """ Rebuild the director tree like src below dest and copy all files like XXX.exts to dest exts:exetens seperate by blank like "jpg png gif" """ fp={} extss=exts.lower().split() for dn,dns,fns in os.walk(src): for fl in fns: if os.path.splitext(fl.lower())[1][1:] in extss: if dn not in fp.keys(): fp[dn]=[] fp[dn].append(fl) for k,v in fp.items(): relativepath=k[len(src)+1:] newpath=os.path.join(dest,relativepath) for f in v: oldfile=os.path.join(k,f) print("拷贝 ["+oldfile+"] 至 ["+newpath+"]") if not os.path.exists(newpath): os.makedirs(newpath) shutil.copy(oldfile,newpath) #用法如下: # #cp_tree_ext(exts,src,dest) # #exts:以空格分隔的字符串,可多个拓展名,如"bat txt" #src:原目录 #dest:目标目录,如果不存在,则建立 cp_tree_ext('doc docx','/home/lincoln/python/copy/source','/home/lincoln/python/copy/target')
只是段代码,直接调用cp_tree_ext(exts,src,dest) 方法即可。
相关推荐
FlySky 2020-11-02
逍遥友 2020-10-26
taiyangshenniao 2020-10-05
flycony 2020-09-23
jacktangj 2020-09-18
YENCSDN 2020-09-15
lsjweiyi 2020-09-14
digwtx 2020-09-14
拾毅者 2020-09-14
zlxcsdn 2020-09-13
weiiron 2020-08-17
amazingbo 2020-08-16
郗瑞强 2020-08-16
lispython 2020-08-16
fengling 2020-08-15
xiesheng 2020-08-02
葫芦小金刚 2020-07-28
StevenSun空间 2020-07-26