Python 遍历目录/子目录的目录,仅打印子目录名称

Python 遍历目录/子目录的目录,仅打印子目录名称,python,pathlib,Python,Pathlib,我有一个具有以下结构的基本目录: name_a/foo/... name_b/bar/... name_c/baz/... 此基本目录有许多名为_X的子文件夹,每个子文件夹中都有一个目录,其中还包含其他文件 我试图得到一个只有子目录名称的列表,即,我的目标是打印: foo bar baz ,但我也在打印父母: name_a name_b name_c foo bar baz 我用这个: from pathlib import target_path = Path("my_ba

我有一个具有以下结构的基本目录:

name_a/foo/...
name_b/bar/...
name_c/baz/...
此基本目录有许多名为_X的子文件夹,每个子文件夹中都有一个目录,其中还包含其他文件

我试图得到一个只有子目录名称的列表,即,我的目标是打印:

foo
bar
baz
,但我也在打印父母:

name_a
name_b
name_c
foo
bar
baz
我用这个:

from pathlib import 

target_path = Path("my_base_dir")
for p in target_path.glob("**/*"):
    if p.is_dir():
        print(p.name) 

任何帮助都将不胜感激。

刚刚修改了您的第三行

import pathlib 

target_path = pathlib.Path("")
for p in target_path.glob("**/*/*"):
    if p.is_dir():
        print(p.name) 

刚刚修改了你的第三行

import pathlib 

target_path = pathlib.Path("")
for p in target_path.glob("**/*/*"):
    if p.is_dir():
        print(p.name) 

您可以使用
访问路径的各个部分。parts

从pathlib导入路径
#“so”是一个包含几个子目录的python版本
Path=list(过滤器(lambda p:p.is_dir(),Path('so').rglob('*'))
#仅深度为2的子目录
如果len(path.parts)==2,则路径中的路径的subdir_name=[path.parts[1]
#['Include','Lib','Scripts','share']
#所有子目录
如果len(Path.parts)>=2,则路径中的路径的所有_subdirs=[Path(*Path.parts[1:])
#[WindowsPath('Include')、WindowsPath('Lib')、WindowsPath('Scripts')、WindowsPath('share'),
#WindowsPath('Lib/site packages')、WindowsPath('Lib/site packages/backcall')、…]
#所有子目录可选
如果len(path.parts)>=2,则路径中的路径的所有子路径=[path.relative_to(path('so'))
#[WindowsPath('Include')、WindowsPath('Lib')、WindowsPath('Scripts')、WindowsPath('share'),
#WindowsPath('Lib/site packages')、WindowsPath('Lib/site packages/backcall')、…]

您可以使用
访问路径的各个部分。部分

从pathlib导入路径
#“so”是一个包含几个子目录的python版本
Path=list(过滤器(lambda p:p.is_dir(),Path('so').rglob('*'))
#仅深度为2的子目录
如果len(path.parts)==2,则路径中的路径的subdir_name=[path.parts[1]
#['Include','Lib','Scripts','share']
#所有子目录
如果len(Path.parts)>=2,则路径中的路径的所有_subdirs=[Path(*Path.parts[1:])
#[WindowsPath('Include')、WindowsPath('Lib')、WindowsPath('Scripts')、WindowsPath('share'),
#WindowsPath('Lib/site packages')、WindowsPath('Lib/site packages/backcall')、…]
#所有子目录可选
如果len(path.parts)>=2,则路径中的路径的所有子路径=[path.relative_to(path('so'))
#[WindowsPath('Include')、WindowsPath('Lib')、WindowsPath('Scripts')、WindowsPath('share'),
#WindowsPath('Lib/site packages')、WindowsPath('Lib/site packages/backcall')、…]
哦,天哪,我差点就有id:)太多了!哦,孩子,我几乎有了身份证:)太多了!