Isaac Davies
Isaac Davies

Reputation: 33

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

Upvotes: 3

Views: 2402

Answers (2)

facelessuser
facelessuser

Reputation: 1734

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

Upvotes: 2

Denver
Denver

Reputation: 639

Ones you have your list of files you can use list comprehension to filter and remove any files that contain 'ER'.

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

Upvotes: 3

Related Questions