pythonfilefnmatch

Exclude files with fnmatch


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.


Solution

  • 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