简体   繁体   English

排除 glob.glob() 中的文件

[英]Excluding files in glob.glob()

I have text files in a folder I need to iterate through and pull data from using python.我在一个文件夹中有文本文件,我需要遍历并使用 python 提取数据。 To get all the path names I am using glob.glob(), except that I need to exclude any files that have 'ER' int he name.为了获取我使用 glob.glob() 的所有路径名,除了我需要排除名称中包含 'ER' 的所有文件。 After looking around I found the [!_] command, however it is not working.环顾四周后,我发现了 [!_] 命令,但它不起作用。 Below is my exact code that is still returning 'ER' files.下面是我仍然返回“ER”文件的确切代码。

files = glob.glob('*[!ER]*.txt')

如果你有你的文件列表,你可以使用列表理解来过滤和删除任何包含“ER”的文件。

files = [f for f in files if 'ER' not in f]

There are other libraries that can do exclusions.还有其他库可以排除。 For instance wcmatch (full disclosure, I'm the author of it) allows you to use exclusion patterns (when enabled via a flag).例如wcmatch (完全公开,我是它的作者)允许您使用排除模式(当通过标志启用时)。 Exclusion patterns are given along with a normal patterns, and it will filter the returned list of files:排除模式与正常模式一起给出,它将过滤返回的文件列表:

from wcmatch import glob
glob.glob(['*.txt', '!*ER*.txt'], flags=glob.N)

Here is a real world example:这是一个真实世界的例子:

from wcmatch import glob
>>> glob.glob(['*.md'], flags=glob.N)
['LICENSE.md', 'README.md']
>>> glob.glob(['*.md', '!*EA*.md'], flags=glob.N)
['LICENSE.md']

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM