0

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)

eyllanesc
  • 235,170
  • 19
  • 170
  • 241
droperto
  • 117
  • 10
  • Possible duplicate of [How to use glob() to find files recursively?](https://stackoverflow.com/questions/2186525/how-to-use-glob-to-find-files-recursively) – norok2 Sep 26 '19 at 01:36

1 Answers1

1

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.

norok2
  • 25,683
  • 4
  • 73
  • 99