Get name (not full path) of subdirectories in python

Question:

There are many posts on Stack Overflow that explain how to list all the subdirectories in a directory. However, all of these answers allow one to get the full path of each subdirectory, instead of just the name of the subdirectory.

I have the following code. The problem is the variable subDir[0] outputs the full path of each subdirectory, instead of just the name of the subdirectory:

import os 


#Get directory where this script is located 
currentDirectory = os.path.dirname(os.path.realpath(__file__))


#Traverse all sub-directories. 
for subDir in os.walk(currentDirectory):
    #I know none of my subdirectories will have their own subfolders 
    if len(subDir[1]) == 0:
        print("Subdirectory name: " + subDir[0])
        print("Files in subdirectory: " + str(subDir[2]))

How can I just get the name of each subdirectory?

For example, instead of getting this:

C:UsersmyusernameDocumentsProgrammingImage-DatabaseCuratedHype

I would like this:

Hype

Lastly, I still need to know the list of files in each subdirectory.

Asked By: Foobar

||

Answers:

Use os.path.basename

for path, dirs, files in os.walk(currentDirectory):
    #I know none of my subdirectories will have their own subfolders 
    if len(dirs) == 0:
        print("Subdirectory name:", os.path.basename(path))
        print("Files in subdirectory:", ', '.join(files))
Answered By: nosklo

You can use os.listdir coupled with os.path.isdir for this.

Enumerate all items in the directory you want and iterate through them while printing out the ones that are directories.

import os
current_directory = os.path.dirname(os.path.realpath(__file__))
for dir in os.listdir(current_directory):
    if os.path.isdir(os.path.join(current_directory, dir)):
        print(dir)
Answered By: Ziyad Edher

Splitting your sub-directory string on '' should suffice. Note that '' is an escape character so we have to repeat it to use an actual slash.

import os

#Get directory where this script is located
currentDirectory = os.path.dirname(os.path.realpath(__file__))

#Traverse all sub-directories.
for subDir in os.walk(currentDirectory):
    #I know none of my subdirectories will have their own subfolders
    if len(subDir[1]) == 0:
        print("Subdirectory name: " + subDir[0])
        print("Files in subdirectory: " + str(subDir[2]))
        print('Just the name of each subdirectory: {}'.format(subDir[0].split('\')[-1]))
Answered By: Arda Arslan
import os
dirList = os.listdir()
for directory in dirList:
    if os.path.isdir(directory):
        print('Directory Name: ', directory)
        print('File List: ', os.listdir(directory))
Answered By: environ