简体   繁体   中英

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.

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

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.

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

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