0 votes
1 view
in Python by (107k points)

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.



 

1 Answer

0 votes
by (47.8k points)
  • You should use pathlib.Path.glob from the pathlib module.Gelow is the code for that:-

from pathlib 

import Path for filename in Path('src').glob('**/*.c'): 

print(filename)

  • Another thing you can do is use glob.glob(). In cases where matching files begin with a dot (.); like files in the current directory or hidden files on Unix based system, use the os.walk solution as mentioned below. You can use fnmatch.fnmatch() instead of glob:

fnmatch.fnmatch():-

Function fnmatch.fnmatch() tests whether the given filename string matches the pattern string and returns a boolean value. If the operating system is case-insensitive, then both parameters will be normalized to all lower-case or upper-case before the comparison is performed.

import os, fnmatch 

def find_files(directory, pattern): 

    for root, dirs, files in os.walk(directory): 

        for basename in files: 

            if fnmatch.fnmatch(basename, pattern): 

                 filename = os.path.join(root, basename)

                yield filename 

for filename in find_files('src', '*.c'): 

    print ('Found C source:', filename)

Related questions

0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
asked Jul 18, 2019 in Python by Sammy (47.8k points)
0 votes
1 answer
Welcome to Intellipaat Community. Get your technical queries answered by top developers !


Categories

...