问题描述
我正在使用Python 3.7.7。
from pathlib import Path
# Get all subdirectories.
p = Path(root_path)
dir_lst = [str(x) for x in p.iterdir() if x.is_dir()]
但是现在我需要获取所有名称以Challen_2013*
之类的模式开头的子目录。
我该怎么办?
解决方法
您可能想使用glob:
import glob
files = glob.glob(f"root_path/{Challen_2013*}")
for file in files:
# do stuff
,
您可以像上一个答案一样使用glob
,或仅使用startswith
来过滤结果:
[str(x) for x in p.iterdir() if x.is_dir() if x.name.startswith("Challen_2013")]
,
有点脏,但是很简单
[str(x) for x in p.iterdir() if x.is_dir() and str(x).startswith('Challen_2013')]