This is what I have:
glob(os.path.join('src','*.c')) but I want to search the subfolders of src. Something like this would work:
glob(os.path.join('src','*.c')) glob(os.path.join('src','*','*.c')) glob(os.path.join('src','*','*','*.c')) glob(os.path.join('src','*','*','*','*.c')) But this is obviously limited and clunky.
Using Glob() function to find files recursivelyglob() or glob. iglob() directly from glob module to retrieve paths recursively from inside the directories/files and subdirectories/subfiles. Note: When recursive is set True “ ** ” followed by path separator ('./**/') will match any files or directories.
glob (short for global) is used to return all file paths that match a specific pattern. We can use glob to search for a specific file pattern, or perhaps more usefully, search for files where the filename matches a certain pattern by using wildcard characters.
pathlib.Path.rglob
Use pathlib.Path.rglob from the the pathlib module, which was introduced in Python 3.5.
from pathlib import Path for path in Path('src').rglob('*.c'): print(path.name) If you don't want to use pathlib, use can use glob.glob('**/*.c'), but don't forget to pass in the recursive keyword parameter and it will use inordinate amount of time on large directories.
For cases where matching files beginning with a dot (.); like files in the current directory or hidden files on Unix based system, use the os.walk solution below.
os.walk
For older Python versions, use os.walk to recursively walk a directory and fnmatch.filter to match against a simple expression:
import fnmatch import os matches = [] for root, dirnames, filenames in os.walk('src'): for filename in fnmatch.filter(filenames, '*.c'): matches.append(os.path.join(root, filename))
For python >= 3.5 you can use **, recursive=True :
import glob for f in glob.glob('/path/**/*.c', recursive=True): print(f) If recursive is
True, the pattern**will match any files and zero or moredirectoriesandsubdirectories. If the pattern is followed by anos.sep, only directories andsubdirectoriesmatch.
Python 3.6 Demo
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With