0

I have a base dir with the following structure:

name_a/foo/...
name_b/bar/...
name_c/baz/...

This base dir has many subfolders with names_X, and inside each of those, there is a single dir that contains also other files.

I´m trying to get a list with only the subdirs names, i.e., my goal is to print:

foo
bar
baz

, but I´m printing also the parents:

name_a
name_b
name_c
foo
bar
baz

I´m using this:

from pathlib import 

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

Any help will be much appreciated.

Maxwell's Daemon
  • 587
  • 1
  • 6
  • 21

2 Answers2

1

Just modified your third line.

import pathlib 

target_path = pathlib.Path("")
for p in target_path.glob("**/*/*"):
    if p.is_dir():
        print(p.name) 
JongHyeon Yeo
  • 879
  • 1
  • 10
  • 18
1

You can access the parts of a path with .parts:

from pathlib import Path

# 'so' is a venv for python containing a few subdirectories
paths = list(filter(lambda p: p.is_dir(), Path('so').rglob('*')))

# only subdirectories with depth 2
subdir_names = [path.parts[1] for path in paths if len(path.parts) == 2]
# ['Include', 'Lib', 'Scripts', 'share']

# all subdirectories
all_subdirs = [Path(*path.parts[1:]) for path in paths if len(path.parts) >= 2]
# [WindowsPath('Include'), WindowsPath('Lib'), WindowsPath('Scripts'), WindowsPath('share'),
#  WindowsPath('Lib/site-packages'), WindowsPath('Lib/site-packages/backcall'), ... ]

# all subdirectories alternative
all_subdirs = [path.relative_to(Path('so')) for path in paths if len(path.parts) >= 2]
# [WindowsPath('Include'), WindowsPath('Lib'), WindowsPath('Scripts'), WindowsPath('share'),
#  WindowsPath('Lib/site-packages'), WindowsPath('Lib/site-packages/backcall'), ... ]
Stefan B
  • 1,617
  • 4
  • 15