2

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.

kaya3
  • 47,440
  • 4
  • 68
  • 97
Bostjan
  • 1,455
  • 3
  • 14
  • 22
  • Getting familiar with wildcards in unix helped me in this regard: https://seankross.com/the-unix-workbench/working-with-unix.html#get-wild – AJMA Sep 11 '18 at 10:02

3 Answers3

2

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
Chris
  • 22,923
  • 4
  • 56
  • 50
  • This works perfectly, thanks. Another error on my part was what needs to be passed in the space of 'Test' in terms of wildcards. Passing '*Test*' did not work – opperman.eric May 04 '22 at 22:44
0

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.

user2707389
  • 817
  • 6
  • 12
  • Hello. This one should actually print only files that have "Test*" pattern in name. What I would like to do is actually exclude them from list. As you mentioned also in your comment, what Chris mentioned did the trick. – Bostjan Mar 07 '18 at 15:20
0

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
Marco
  • 1,952
  • 1
  • 17
  • 23