python 拷贝特定后缀名文件,并保留原始目录结构的实例
作者:迦蓝叶 时间:2021-08-30 04:17:46
如下所示:
#!/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')
只是段代码,直接调用cp_tree_ext(exts,src,dest) 方法即可。
来源:https://blog.csdn.net/soslinken/article/details/54015578
标签:python,文件,后缀名,目录,结构
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
电子商务搜索LIST页面用户体验设计
2010-08-03 12:57:00
![](https://img.aspxhome.com/file/UploadPic/20108/3/20108313022804s.jpg)
25个值得收藏的Python文本处理案例
2022-06-19 15:38:29
Python语言规范之Pylint的详细用法
2022-11-26 03:12:25
![](https://img.aspxhome.com/file/2023/8/78588_0s.jpg)
Python中的十大图像处理工具(小结)
2021-02-04 09:17:51
![](https://img.aspxhome.com/file/2023/2/82612_0s.jpg)
Python爬取商家联系电话以及各种数据的方法
2023-07-24 18:39:38
![](https://img.aspxhome.com/file/2023/0/66450_0s.jpg)
Python 一行代码能实现丧心病狂的功能
2023-07-25 08:32:17
![](https://img.aspxhome.com/file/2023/8/61428_0s.png)
对python中的iter()函数与next()函数详解
2022-01-29 19:05:36
python fire库的使用实例教程
2023-08-24 14:01:22
![](https://img.aspxhome.com/file/2023/0/61760_0s.png)
Python入门_浅谈数据结构的4种基本类型
2021-01-11 19:12:28
ASP:判断访问是否来自搜索引擎的函数
2008-03-12 11:39:00
ThinkPHP5&5.1实现验证码的生成、使用及点击刷新功能示例
2023-11-17 02:54:39
用Python抢火车票的简单小程序实现解析
2023-09-06 06:31:28
python 使用OpenCV进行简单的人像分割与合成
2021-06-16 20:46:39
![](https://img.aspxhome.com/file/2023/8/75128_0s.png)
Python 保存矩阵为Excel的实现方法
2022-07-23 07:05:00
python本地文件服务器实例教程
2022-07-31 16:38:17
![](https://img.aspxhome.com/file/2023/7/64607_0s.jpg)
FrontPage XP中的设计技巧
2008-07-17 10:49:00
Python中如何实现MOOC扫码登录
2021-10-08 14:24:50
![](https://img.aspxhome.com/file/2023/1/66861_0s.png)
python sklearn包——混淆矩阵、分类报告等自动生成方式
2022-05-29 12:19:27
![](https://img.aspxhome.com/file/2023/2/67332_0s.jpg)
python基础之错误和异常处理
2021-07-28 05:46:15
![](https://img.aspxhome.com/file/2023/3/65933_0s.png)
PHP实现PDF转图片的方法详解
2023-05-26 19:59:51