简体   繁体   中英

Excluding files in glob.glob()

I have text files in a folder I need to iterate through and pull data from using 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. After looking around I found the [!_] command, however it is not working. Below is my exact code that is still returning 'ER' files.

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). 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']

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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