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

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.

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

Need Your Help

Notification vibrating when screen is on even when I'm on the phone

android android-notifications android-vibration

I have an app that starts a notification at a certain time, the user can choose the ringtone of the notification, when I put my phone on mute mode and the screen was off the notification didn't vib...

ms access custom multiple select list box in a form bound to sql server table

sql-server-2008 ms-access-2010

I have a table in sql server 2008 called Program, some of the fields of program table are: