How to Get List of Subdirectories Names in Python


In this article, we’ll see how to get a list of subdirectories names in Python.

Source Code

#! /usr/bin/env python3
# -*- coding: utf-8 -*-

import os.path

def TraverseDir(path):
    ab = []

    if (os.path.exists(path)):
        files = os.listdir(path)
        for file in files:
            m = os.path.join(path, file)
            if (os.path.isdir(m)):
                h = os.path.split(m)
                print(h[1],)
                ab.append(h[1])
        print(ab)

TraverseDir("C:test")

Output:

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments