使用glob **根据递归参数匹配文件扩展名

如何解决使用glob **根据递归参数匹配文件扩展名

我正在尝试使用全局模式匹配具有给定扩展名的文件。 glob函数(来自glob模块)具有参数“递归”,似乎应该打开或关闭搜索子目录。但是,只有在recursive = False的情况下,才能在当前目录中构造与当前类型的文件相匹配的glob模式,而在recursive = True的情况下,也不能在子目录中与该文件类型相匹配。

folder='C:\\test'
glob(folder+'**.ext',recursive=True) #fails to find any files
glob(folder+'\\**.ext',recursive=True) #fails to search subfolders
glob(folder+'\\**',recursive=True) #fails to filter by type
glob(folder+'\\**\\*.ext',recursive=False) #searches subfolders when it shouldn't
glob(folder+'**\\*.ext',recursive=True) #fails to search subfolders

基于文档

“ **”将匹配任何文件以及零个或多个目录

因此,我希望**的行为类似于*,但它也匹配斜杠。但是,它没有按预期运行(请参阅上面的前两个示例)。

为什么**不能按预期工作,并且有一种模式可以匹配某些文件类型,并且仅可以使用递归参数来打开或关闭递归?

解决方法

我认为您误解了recursive=True的含义。它用于允许**表示搜索可变深度的子目录-glob(folder+'\\**\\*.ext',recursive=True)将在起始文件夹或其下方的任何位置找到任何*.ext个文件。如果没有recursive=True,将以正常方式解释**,每个*的含义是匹配\ 和{因此,{1}}等同于**,换句话说,*将搜索从起始文件夹向下精确到子目录一级的任何glob(folder+'\\**\\*.ext',recursive=False)文件在起始文件夹本身或更深的子目录中。

究竟应该使用哪种取决于您要查找的内容-确实可能是您需要使用*.ext语句在不同的情况下进行选择-但是没有用于的情况将if**一起使用,因为在这种情况下,它等效于recursive=False

最可能有用的选项是:

*

glob(folder+'\\*.ext',recursive=False) # search in top folder only glob(folder+'\\*\\*.ext',recursive=False) # search exactly one level down glob(folder+'\\**\\*.ext',recursive=True) # search to arbitrary depth 可以省略,因为它是默认值。

如果要使用布尔选项在两个选项之间进行选择,则始终可以编写自己的包装函数,例如:

,recursive=False

(在类似Unix的操作系统中,请阅读上文def myglob(folder,pattern,subdirs=False): if subdirs: return glob(f'{folder}\\**\\{pattern}',recursive=True) else return glob(f'{folder}\\{pattern}') print(myglob(folder,'*.ext',subdirs=False)) print(myglob(folder,subdirs=True)) print(myglob(folder,'*.ext')) # same as subdirs=False in this example 的{​​{1}}。)

,

全局'**'的操作

可以在here中找到glob源代码。除注释外,“ **”仅出现在_isrecursive函数中:

def _isrecursive(pattern):
    if isinstance(pattern,bytes):
        return pattern == b'**'
    else:
        return pattern == '**'

由于_isrecursive函数使用相等运算符检查'',因此''仅在完整的'pattern'时才按预期运行。 _isrecursive函数在源代码中被调用4次,对整个glob调用一次,对“ basename”调用3次,定义为:

dirname,basename = os.path.split(pathname)

这是递归调用,一次将路径的尾部分开,每次,基名都是斜杠后面的所有内容(在技术上是os.sep,对于Windows或POSIX,它是\)。这意味着,为了使“ **”按所述方式运行,它不得与除斜杠之外的其他任何东西相邻。

如果递归未明确设置为True,则'**'='*'+'*'='*',因为'*'匹配0个或多个非斜杠字符。

匹配扩展

由于'**'的工作方式,必须使用它表示整个glob的级别。由于r'folder \ ** \ *。ext' 表示 0个或更多级别,因此将匹配“ folder”以及子文件夹中的文件。但是,如果未将递归设置为true,则此模式将仅匹配子文件夹第一级中的文件。

'**。ext'将不起作用,因为'**'并不孤单。剩下以下选项:

  1. 使用其他库(例如os.walk,pathlib.glob等)

  2. [f for f in glob(folder+'\\**',recursive=subdirs) if f.endswith('.ext')]

  3. glob(folder+('\\**' if subdirs else '')+'\\*.ext,recursive=True)

    或等效地,

    if recursive:
        glob(folder+'\\**\\*.ext',recursive=True)
    else:
        glob(folder+'\\*.ext')
    
  4. glob(folder+'\\..\\**\\*.ext',recursive=subdirs) #not recommended since it will also match files in sibling folders

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


依赖报错 idea导入项目后依赖报错,解决方案:https://blog.csdn.net/weixin_42420249/article/details/81191861 依赖版本报错:更换其他版本 无法下载依赖可参考:https://blog.csdn.net/weixin_42628809/a
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下 2021-12-03 13:33:33.927 ERROR 7228 [ main] o.s.b.d.LoggingFailureAnalysisReporter : *************************** APPL
错误1:gradle项目控制台输出为乱码 # 解决方案:https://blog.csdn.net/weixin_43501566/article/details/112482302 # 在gradle-wrapper.properties 添加以下内容 org.gradle.jvmargs=-Df
错误还原:在查询的过程中,传入的workType为0时,该条件不起作用 <select id="xxx"> SELECT di.id, di.name, di.work_type, di.updated... <where> <if test=&qu
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct redisServer’没有名为‘server_cpulist’的成员 redisSetCpuAffinity(server.server_cpulist); ^ server.c: 在函数‘hasActiveC
解决方案1 1、改项目中.idea/workspace.xml配置文件,增加dynamic.classpath参数 2、搜索PropertiesComponent,添加如下 <property name="dynamic.classpath" value="tru
删除根组件app.vue中的默认代码后报错:Module Error (from ./node_modules/eslint-loader/index.js): 解决方案:关闭ESlint代码检测,在项目根目录创建vue.config.js,在文件中添加 module.exports = { lin
查看spark默认的python版本 [root@master day27]# pyspark /home/software/spark-2.3.4-bin-hadoop2.7/conf/spark-env.sh: line 2: /usr/local/hadoop/bin/hadoop: No s
使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams['font.sans-serif'] = ['SimHei'] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -> systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping("/hires") public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate<String
使用vite构建项目报错 C:\Users\ychen\work>npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-