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

时间:2018-07-10 19:23:27

标签: python python-3.x filesystems subdirectory python-os

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

我想要这样:

  

炒作

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

4 个答案:

答案 0 :(得分: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 :(得分: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))

答案 2 :(得分:1)

您可以结合使用os.listdiros.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)

答案 3 :(得分:0)

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