python – List Directories and get the name of the Directory

python – List Directories and get the name of the Directory

This will print all the subdirectories of the current directory:

print [name for name in os.listdir(.) if os.path.isdir(name)]

Im not sure what youre doing with split(-), but perhaps this code will help you find a solution?

If you want the full pathnames of the directories, use abspath:

print [os.path.abspath(name) for name in os.listdir(.) if os.path.isdir(name)]

Note that these pieces of code will only get the immediate subdirectories. If you want sub-sub-directories and so on, you should use walk as others have suggested.

import os
for root, dirs, files in os.walk(top, topdown=False):
    for name in dirs:
        print os.path.join(root, name)

Walk is a good built-in for what you are doing

python – List Directories and get the name of the Directory

I liked the answer of @RichieHindle but I add small fix for it

import os

folder = ./my_folder

sub_folders = [name for name in os.listdir(folder) if os.path.isdir(os.path.join(folder, name))]

print(sub_folders)

otherwise its not really work

Leave a Reply

Your email address will not be published. Required fields are marked *