Home >Backend Development >Python Tutorial >Python copies files with specific suffixes and retains the original directory structure.

Python copies files with specific suffixes and retains the original directory structure.

不言
不言Original
2018-05-02 15:53:101738browse

This article mainly introduces examples of copying files with specific suffix names in Python and retaining the original directory structure. It has certain reference value. Now I share it with you. Friends in need can refer to it

is as follows:

#!/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')

is just a piece of code, directly call the cp_tree_ext(exts,src,dest) method. Can.


The above is the detailed content of Python copies files with specific suffixes and retains the original directory structure.. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn