Python copies specific suffix files and preserves instances of the original directory structure

Source: Internet
Author: User
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.


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.