获取 python 中子目录的名称(非完整路径)

Get name (not full path) of subdirectories in python

Stack Overflow 上有很多帖子解释了如何列出目录中的所有子目录。但是,所有这些答案都允许获得每个子目录的完整路径,而不仅仅是子目录的名称。

我有以下代码。问题是变量 subDir[0] 输出每个子目录的完整路径,而不仅仅是子目录的名称:

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

我怎样才能得到每个子目录的名称?

例如,而不是得到这个:

C:\Users\myusername\Documents\Programming\Image-Database\Curated\Hype

我想要这个:

Hype

最后,我还需要知道每个子目录中的文件列表。

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

您可以为此使用 os.listdir coupled with os.path.isdir

枚举所需目录中的所有项目并遍历它们,同时打印出作为目录的项目。

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)

'\' 上拆分您的子目录字符串就足够了。请注意,'\' 是一个转义字符,因此我们必须重复它才能使用实际的斜杠。

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]))
import os
dirList = os.listdir()
for directory in dirList:
    if os.path.isdir(directory) == True:
        print('Directory Name: ', directory)
        print('File List: ', os.listdir(directory))