Search code examples
pythonpython-3.xfilesystemssubdirectorypython-os

Get name (not full path) of subdirectories in python


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:\Users\myusername\Documents\Programming\Image-Database\Curated\Hype

I would like this:

Hype

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


Solution

  • 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]))