Python – Filter directory contents

short and sweet, this python snippet will return a list containing your filtered directory


import re
import os

filter = ".*" + searchstr + ".*"
m = re.compile(filter,re.I) #if you want to ignore case use re.I, otherwise remove it
filter(m.search,os.listdir(os.getcwd()))

#that's it, you can see that the reason for compiling the regex is so you can use m.search as a function pointer which accepts the list of all items in the directory

This entry was posted in Python, regex and tagged , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

*


*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>