How to search a folder for a file name that matches a regular expression using Python?

I find it difficult to write a function that will look through the directory for a file that matches a specific regular expression (which I compiled with '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 particular regular expression? An example is much appreciated. Thanks in advance.

+3
source share
4 answers

Here all files starting with two digits and ending with gif will be found, you can add files to the global list if you want:

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
+9
source
+2

, , , , glob, .

+1

One of the founders of Stackoverflow is a big fan of JGSoft 's RegexBuddy. I tried it on my own when I wrote about working with a script file, and created the best regular expression to work in a simple language of your choice. If you are having trouble developing the most regular expression, this is a good tool to test your logic. I think I'm also a big fan.

+1
source

All Articles