Foobar
Foobar

Reputation: 8467

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.

Upvotes: 4

Views: 6458

Answers (4)

environ
environ

Reputation: 1

import os
dirList = os.listdir()
for directory in dirList:
    if os.path.isdir(directory):
        print('Directory Name: ', directory)
        print('File List: ', os.listdir(directory))

Upvotes: 0

Arda Arslan
Arda Arslan

Reputation: 1361

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

Upvotes: 3

Ziyad Edher
Ziyad Edher

Reputation: 2150

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)

Upvotes: 1

nosklo
nosklo

Reputation: 222862

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

Upvotes: 3

Related Questions