选择性拷贝
選擇性拷貝
#編寫一個程序,遍歷一個目錄樹,查找特定擴(kuò)展名的文件(諸如.pdf 或.jpg)。不論這些文件的位置在哪里,將它們拷貝到一個新的文件夾中。
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Date : 2021-02-20 10:08:58 # @Author : Yang chunyu (ycyyangchunyu@qq.com) # @Link : https://blog.csdn.net/weixin_49374896 # @Version : $Id$import os,shutil#創(chuàng)建新文件夾 def makefilefolder(path): isExists=os.path.exists(path)if not isExists:os.makedirs(path) folder='D:\\python_test\\test' det_folder='D:\\python_test\\test2' #這里需要創(chuàng)建D:\\python_test\\test2,如果D:\\python_test\\test2不存在,系統(tǒng)會認(rèn)為test2是一個文件而非目錄 makefilefolder(det_folder) folder_basename=os.path.basename(folder) for folder_name,sub_folder,file_names in os.walk(folder):for file_name in file_names:if file_name.endswith('.ipynb'):#name是原將要復(fù)制過去的完整文件名name=os.path.join(folder_name,file_name)print('%s is copying' % (name))#這里判斷.ipynb是直接在folder目錄下還是在其中的子目錄下new_folder_basename=os.path.basename(folder_name)if folder_basename!=new_folder_basename:#如果實(shí)在子目錄下,則在目的目錄中創(chuàng)建子目錄new_det_folder=os.path.join(det_folder,new_folder_basename)print('copy to %s' % (new_det_folder))makefilefolder(new_det_folder)shutil.copy(name,new_det_folder)else:print('copy to %s' % (det_folder))shutil.copy(name,det_folder)D:\python_test\test
D:\python_test\test2
-MyH4faXP-1613794361602)]
D:\python_test\test2
總結(jié)
- 上一篇: 跨境电商企业如何招聘、留住人才?
- 下一篇: 【翻】What Is Undo? 201