Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I search through a folder for the filename that matches a regular expression using Python?

Tags:

python

regex

I am having some difficulty writing a function that will search through a directory for a file that matches a specific regular expression (which I have compiled using 're.compile'). So my question is: How do I search through a directory (I plan to use os.walk) for a file that matches a specific regular expression? An example would be very much appreciated. Thanks in advance.

like image 815
Amara Avatar asked Jan 20 '26 01:01

Amara


1 Answers

This will find all files starting with two digits and ending in gif, you can add the files into a global list, if you wish:

import re
import os
r = re.compile(r'\d{2}.+gif$')
for root, dirs, files in os.walk('/home/vinko'):
  l = [os.path.join(root,x) for x in files if r.match(x)]
  if l: print l #Or append to a global list, whatever
like image 192
Vinko Vrsalovic Avatar answered Jan 22 '26 15:01

Vinko Vrsalovic



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!