Reputation: 1575
I am creating a loop in Python that runs through all files in specific directory using fnmatch.filter()
. Currently I am going through all .csv files in specific folder as following:
for file_source in fnmatch.filter(os.listdir(source_dir), "*.csv")
What I would like to do is exclude files with pattern "Test*". Is that somehow possible to do with fnmatch. In worst case I would just create another internal if loop, but would prefer a cleaner solution.
Upvotes: 2
Views: 2831
Reputation: 2020
How about something like this:
import re
import os
for file in os.listdir('./'):
rex = '^((?!Test).)*\.csv$'
reobj = re.compile(rex)
obj = reobj.match(file)
if obj != None:
print obj.string
Upvotes: 0
Reputation: 827
I am not familiar with fnmatch but I tried
if fnmatch.fnmatch(file, 'Test*'):
print(file)
And it worked all right. You could also use list comprehension as suggested by Chris.
Upvotes: 0
Reputation: 23171
You can use a list comprehension to filter the filenames:
for file_source in [x for x in fnmatch.filter(os.listdir(source_dir), "*.csv") if 'Test' not in x ] :
pass
Upvotes: 2