Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 380
Roymunson Avatar asked Oct 19 '25 21:10

Roymunson


2 Answers

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]))
like image 69
Arda Arslan Avatar answered Oct 21 '25 11:10

Arda Arslan


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))
like image 26
nosklo Avatar answered Oct 21 '25 09:10

nosklo