Quantcast
Viewing all articles
Browse latest Browse all 5

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.


Viewing all articles
Browse latest Browse all 5

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>