简体   繁体   中英

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 ?

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*')]

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