How to search for specific extension of a filename matching a certain pattern

133 views Asked by At

I have a bunch of files organized liked so:

fre_3434_a2.txt
fre_3434_a2.csv
fre_3546_a2.txt...

I want to find the file that matches the pattern "3434" and the extension ".txt" I've tried this but it hasn't worked:

for root, dirs, filenames in os.walk('.'):
for filename in fnmatch.filter(filenames, '[3434]*.txt'):
    print(os.path.join(root, filename))

How can I search for a specific pattern in a file as well as a specific extension?

1

There are 1 answers

0
Carles Mitjans On BEST ANSWER

Try this:

for root, dirs, filenames in os.walk('.'):
    for filename in fnmatch.filter(filenames, '*3434*.txt'):
        print(os.path.join(root, filename))

"*3434*.txt" instead of [3434]*.txt.