【问题标题】:Get name (not full path) of subdirectories in python获取python中子目录的名称(不是完整路径)
【发布时间】:2018-07-10 19:23:26
【问题描述】:

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

我想要这个:

炒作

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

【问题讨论】:

  • 对于第一部分,将str 拆分为'\' 并取最后一个元素。即sample_str.split('\')[-1]

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


【解决方案1】:

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

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】:

    使用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】:

      您可以为此使用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)
      

      【讨论】:

        【解决方案4】:
        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))
        

        【讨论】:

          猜你喜欢
          • 2022-11-11
          • 2015-02-01
          • 1970-01-01
          • 1970-01-01
          • 2010-10-14
          • 2022-07-28
          • 1970-01-01
          • 2015-12-26
          • 1970-01-01
          相关资源
          最近更新 更多