-1

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?

VansFannel
  • 45,055
  • 107
  • 359
  • 626

3 Answers3

1

You might want to use glob:

import glob
files = glob.glob(f"root_path/{Challen_2013*}")
for file in files:
# do stuff
MichaelJanz
  • 1,775
  • 2
  • 8
  • 23
1

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")]
Roy2012
  • 11,755
  • 2
  • 22
  • 35
  • can be replace str(x) to x.as_posix(): [x.as_posix() for x in p.iterdir() if x.is_dir() if x.name.startswith("Challen_2013")] – britodfbr Apr 07 '22 at 18:27
0

A bit dirty, but simple

[str(x) for x in p.iterdir() if x.is_dir() and str(x).startswith('Challen_2013')]

ThibautM
  • 71
  • 3
  • That's the answer bigbounty posted as a comment and it isn't working since the string does not start with that substring. It's a subdirectory. The string starts with the root path. quickedit: Comment was edited. It works with `x.name.startswith()`. But `str(x).startswith()` is still a wrong answer. – Tin Nguyen Aug 11 '20 at 07:56