List Visible And Hidden Sub-Directories Non-Recursively In Python

March - 2022

Note that this just gives you the names. No extra paths come through.

This code:

from os import listdir
from os.path import isdir
from os.path import join

source_dir = "example_dir"

directories = [d for d in listdir(source_dir) if isdir(join(source_dir, d))]

print(directories)

Will return:

['.invisible-dir', 'dir-2', 'dir-1']

Give a tree of files like:

example_dir
├── .invisible-dir
│   ├── file-10.txt
│   └── file-9.txt
├── .invisible-file-1.txt
├── .invisible-file-2.txt
├── dir-1
│   ├── file-3.txt
│   └── file-4.txt
├── dir-2
│   ├── dir-3
│   │   ├── file-7.txt
│   │   └── file-8.txt
│   ├── file-5.txt
│   └── file-6.txt
├── file-1.txt
└── file-2.txt