python 拷貝特定尾碼名檔案,並保留原始目錄結構的執行個體

來源:互聯網
上載者:User
這篇文章主要介紹了關於python 拷貝特定尾碼名檔案,並保留原始目錄結構的執行個體,有著一定的參考價值,現在分享給大家,有需要的朋友可以參考一下

如下所示:

#!/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: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) 方法即可。


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.