This article mainly introduces the Python copy specific suffix file, and preserves the original directory structure of the instance, has a certain reference value, now share to everyone, the need for friends can refer to
As shown below:
#!/usr/bin/python#-*-coding:utf-8-*-import osimport shutildef cp_tree_ext ( Exts,src,dest): "" Rebuild the director tree like SRC below dest and copy all files like xxx.exts to Dest Exts:exeten s 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:] ' 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 ("Copy [" +oldfile+ "] to [" +newpath+ "]") if not os.path.exists (NewPath): Os.makedirs (NewPath) shutil.copy (Oldfile,newpath) #用法如下: # #cp_tree_ext (exts,src,dest) # #exts: separated by spaces String, can be multiple extension names, such as "Bat txt" #src: Original directory #dest: Target directory, if not present, then establish Cp_tree_ext (' Doc docx ', '/home/lincoln/python/copy/source ', '/ Home/lincoln/python/copy/target ')
Just a piece of code, call the Cp_tree_ext (Exts,src,dest) method directly.