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.
views:
304answers:
4How do I search through a folder for the filename that matches a regular expression using Python?
Read about the RE pattern's
match
method.Read all answers to How do I copy files with specific file extension to a folder in my python (version 2.5) script?
Pick one that uses
fnmatch
. Replacefnmatch
withre.match
. This requires careful thought. It's not a cut-and-paste.Then, ask specific questions.
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
If the pattern you have to match is simple enough to grab with filesystem wildcards, I recommend you take a look at the glob module, which exists for this exact purpose.
One of the Stackoverflow founders is a big fan of RegexBuddy from JGSoft. I tried it on a whim when i was writing a simple file moving script at work, and it makes generating the best regex for a job quite easy in the language of your choice. If you're having trouble with developing the regex itself this is a nice tool to check your logic. I guess I'm a big fan now as well.