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

问题描述 投票:1回答:4

[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

我想要这样:

炒作

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

python python-3.x filesystems subdirectory python-os
4个回答
2
投票

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

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

1
投票

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

1
投票

您可以将os.listdiros.listdir结合使用。

枚举所需目录中的所有项目,并在打印出目录中的项目时对其进行遍历。

os.path.isdir

0
投票
os.path.isdir
© www.soinside.com 2019 - 2024. All rights reserved.