代码之家  ›  专栏  ›  技术社区  ›  Foobar

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

  •  1
  • Foobar  · 技术社区  · 7 年前

    堆栈溢出上有许多文章解释如何列出目录中的所有子目录。然而,所有这些答案都允许我们 完整路径 而不仅仅是子目录的名称。

    我有以下代码。问题是变量 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

    我想要这个:

    炒作

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

    3 回复  |  直到 7 年前
        1
  •  2
  •   Arda Arslan    7 年前

    在上拆分子目录字符串 '\' 是一个转义字符,所以我们必须重复它才能使用实际的斜线。

    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]))
    
        2
  •  1
  •   nosklo    7 年前

    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))
    
        3
  •  1
  •   Ziyad Edher    7 年前

    你可以用 os.listdir 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)