Calmcode - pathlib: glob


1 2 3 4 5 6 7

You can iterate over files and folders that match a pattern by using the .glob() method on a path. An example is listed below;

[p for p in Path().glob("data/*/*.json")]

Note the power of having the list comprehension. Every p in the loop below is a Path-object. This means that we can apply all methods on it that we mentioned before. Here's an example;

[p.parent for p in Path().glob("data/*/*.json")]

But you can do anything you'd like here. For example, maybe we also would like to allow for .csv files.

[p for p in Path().glob("data/*/*") if p.suffix in ('.csv', '.json')]

Comprehensions are powerful, also with Path.glob(). There's even a more powerful setting that you can do by using ** instead of *. Try it;

[p for p in Path().glob("**/*.json")]

The results will now be found recursively in all folders.