You can use the glob . It allows you to match patterns by file names and does exactly what you ask.
import glob for fpath in glob.glob(mypath): print fpath
For example, I have a directory with files named google.xml, google.json and google.csv.
I can use glob as follows:
>>> import glob >>> glob.glob('g*gle*') ['google.json', 'google.xml', 'google.csv']
Note that glob uses the fnmatch module, but has a simpler interface and it maps paths instead of file names.
You can search for relative paths and not use os.path.join . In the above example, if I go to the parent directory and try to match the file names, it returns relative paths:
>>> import os >>> import glob >>> os.chdir('..') >>> glob.glob('foo/google*') ['foo/google.json', 'foo/google.xml', 'foo/google.csv']
source share