Search code examples
pythonpathlib

Get all subdirectories that match pattern


I'm using Python 3.7.7.

I have this code that get all the subdirectories:

from pathlib import Path

# Get all subdirectories.
p = Path(root_path)
dir_lst = [str(x) for x in p.iterdir() if x.is_dir()]

But now I need to get all the subdirectories which name starts with a pattern like Challen_2013*.

How can I do it?


Solution

  • You can use glob as in the previous answer, or just use startswith to filter the results:

    [str(x) for x in p.iterdir() if x.is_dir() if x.name.startswith("Challen_2013")]