misguided
misguided

Reputation: 3789

Recursively find files in python

I have run the following code which just searches for the current folder

for file in os.listdir("/folder/test"):
    if fnmatch.fnmatch(file, 'text*'):
        print file

How do I search for all sub folders as well ?

Upvotes: 2

Views: 109

Answers (1)

thefourtheye
thefourtheye

Reputation: 239443

You can use os.walk like this

for dirpath, dirnames, filenames in os.walk("/folder/test"):
    for file in filenames:
        if fnmatch.fnmatch(file, 'text*'):
            print file

If you just want to get all the files,

from os import walk, path
from fnmatch import fnmatch
[path.join(dpath, file) for dpath, _, files in os.walk("/folder/test") for file in files if fnmatch(file, 'text*')]

Upvotes: 3

Related Questions