Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regular Expressions in Python for match files in a folder

Tags:

python

regex

I want to match all the files in a folder using regular expressions for some reason: I used this:

re.compile(r'\.*$')

But this is also matching hidden files and temp files. Is there a better option?

like image 787
madCode Avatar asked Aug 21 '26 14:08

madCode


2 Answers

This makes the assumption that you're wanting to do something with these file names. As someone mentioned in the comments you should use glob. Since I'm not sure what you're going for with the 'temp' files this was the simplest thing. It will return no hidden files. Files is a list of file paths from your current working directory.

import os, glob
files = [f for f in glob.glob('./*') if os.path.isfile(f)]
like image 94
keiththomps Avatar answered Aug 24 '26 05:08

keiththomps


Try re.compile(r'\w+\.*\w*') to match alphanumeric file names with a possible dot extension.

\w+ matches one or more alphanumeric file names [a-zA-Z0-9_]

\.* matches zero or more '.' characters

\w* matches zero or more file extension alphanumeric characters.

Kodos is an excellent Python regular expression developer/debugger.

like image 20
David Pointer Avatar answered Aug 24 '26 03:08

David Pointer