droperto
droperto

Reputation: 152

How to list all files with a certain extension recursively?

I want to retrieve a list of files (filtered by extension) inside a directory (recursively).

I have the solution below but I am confident there is a cleaner way to do that. Probably a simple glob expression that I am missing but any better solution is fine. Better in this scenario is readability (self-documenting) not performance.

I know this example is very simple, but of course it is part of a more complex scenario.

files = glob.glob('documents/*.txt') + glob.glob('documents/**/*.txt')

I'd expect something like

files = glob.glob('playbooks/(**/)?*.yml')

(just an example, that does not work)

Upvotes: 0

Views: 69

Answers (1)

norok2
norok2

Reputation: 26956

To make use of the ** specifier in glob.glob() you need to explicitly set recursive parameter to True, e.g.:

glob.glob('Documents/**/*.txt', recursive=True)

From the official doc:

If recursive is true, the pattern “**” will match any files and zero or more directories, subdirectories and symbolic links to directories. If the pattern is followed by an os.sep or os.altsep then files will not match.

Upvotes: 1

Related Questions