简体   繁体   中英

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.

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
  1. Read about the RE pattern's match method.

  2. Read all answers to How do I copy files with specific file extension to a folder in my python (version 2.5) script ?

  3. Pick one that uses fnmatch . Replace fnmatch with re.match . This requires careful thought. It's not a cut-and-paste.

  4. Then, ask specific questions.

如果你必须匹配的模式很简单,可以使用文件系统通配符,我建议你看一下glob模块,它就是为了这个目的而存在的。

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM