1200字范文,内容丰富有趣,写作的好帮手!
1200字范文 > python获取文件夹下指定后缀名文件列表(可手工设定是否遍历子文件夹)cmd复制文件命

python获取文件夹下指定后缀名文件列表(可手工设定是否遍历子文件夹)cmd复制文件命

时间:2022-07-06 13:38:16

相关推荐

python获取文件夹下指定后缀名文件列表(可手工设定是否遍历子文件夹)cmd复制文件命

打算写一个替换文件的程序,该文件可能在不同文件夹路径,使用python操作肯定最方便,特此简单整理封装了两个python函数和一个cmd复制文件的命令方法,供自己翻阅或来者参考 辉 .8.9。

.8.10号发现bug如下:

空字符串 用in 判断的时候居然是True,这个很明显不是我们期待的(具体原因是啥没有深究)。将其修改为==号即可,如下:

返回文件列表:

import osdef GetFileFromThisRootDir(dir,ext = None,isSubDir = True):'''获取指定文件夹下指定后缀的文件名,:param dir: 文件夹路径:param ext: 后缀名:param isSubDir: 是否遍历该文件夹下子文件夹,ture为遍历子文件夹,false为不遍历子文件夹:return: 文件路径列表'''allfiles = []needExtFilter = (ext != None)if isSubDir == True:#遍历子文件夹for root,dirs,files in os.walk(dir):for filespath in files:filepath = os.path.join(root, filespath)extension = os.path.splitext(filepath)[1][1:]#if needExtFilter and extension in ext:if needExtFilter and (extension == ext): # 空字符串用in 判别会有错误allfiles.append(filepath)elif not needExtFilter:allfiles.append(filepath)else:#不遍历子文件夹for files in os.listdir(dir):filepath = os.path.join(dir,files)if os.path.isfile(filepath):# print("是文件!")#如果是文件,则进行后缀提取,再判别extension = os.path.splitext(filepath)[1][1:]#if needExtFilter and extension in ext:if needExtFilter and (extension == ext): # 空字符串用in 判别会有错误allfiles.append(filepath)elif not needExtFilter:allfiles.append(filepath)# else:#print("不是文件")return allfiles

返回字典:key:文件名,value:文件路径

import osdef GetFileFromThisRootDirToDict(dir,ext = None,isSubDir = True):'''获取指定文件夹下指定后缀的文件名,:param dir: 文件夹路径:param ext: 后缀名:param isSubDir: 是否遍历该文件夹下子文件夹,ture为遍历子文件夹,false为不遍历子文件夹:return: 文件路径字典'''allfiles = {}needExtFilter = (ext != None)if isSubDir == True:#遍历子文件夹for root,dirs,files in os.walk(dir):for filespath in files:filepath = os.path.join(root, filespath)extension = os.path.splitext(filepath)[1][1:]#if needExtFilter and extension in ext:if needExtFilter and (extension == ext): # 空字符串用in 判别会有错误allfiles[os.path.basename(filepath)]=filepath# allfiles.append(filepath)elif not needExtFilter:allfiles[os.path.basename(filepath)] = filepath# allfiles.append(filepath)else:#不遍历子文件夹for files in os.listdir(dir):filepath = os.path.join(dir,files)if os.path.isfile(filepath):# print("是文件!")#如果是文件,则进行后缀提取,再判别extension = os.path.splitext(filepath)[1][1:]#if needExtFilter and extension in ext:if needExtFilter and (extension == ext): # 空字符串用in 判别会有错误allfiles[os.path.basename(filepath)] = filepath# allfiles.append(filepath)elif not needExtFilter:allfiles[os.path.basename(filepath)] = filepath# allfiles.append(filepath)# else:#print("不是文件")return allfiles

感觉字典类型比较好用一些,配合window系统的cmd窗口自带的复制函数copy或者xcopy

这里提供一个覆盖覆盖的方法

功能:复制该文件夹下所有文件/文件夹 到指定文件/文件夹下,如果遇到同名的文件则不提示的覆盖xcopy 路径1(原文件路径) 路径2(要复制的文件路径) /ey或xcopy 路径1(原文件路径) 路径2(要复制的文件路径) /e /y命令样例:xcopy G:\0809\SuperXView2.0\help\* F:\SuperX2.0\help\* /e /y释义:/e 复制所有子目录,包括空目录。/y 禁止提示您确认要覆盖现存的目标文件

python获取文件夹下指定后缀名文件列表(可手工设定是否遍历子文件夹)cmd复制文件命令使用

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。