【问题标题】:Python OS - using 'os.listdir' to view a directory that returns a list of folders. How do I view the contents of the subfolders?Python OS - 使用“os.listdir”查看返回文件夹列表的目录。如何查看子文件夹的内容?
【发布时间】:2021-03-10 21:27:21
【问题描述】:

我被设置了一个挑战来浏览一个包含大部分空文件夹的目录 - 标志(答案)在其中一个。我使用 os 模块查看了所有文件夹的名称——它们都被命名为“文件夹”加上一个 1 到 200 之间的数字。如何查看其中的内容?

【问题讨论】:

  • 你可能不想看这个:stackoverflow.com/a/973488/12203337
  • 通过提供您迄今为止尝试过的内容来为您的问题添加更多详细信息。
  • 我做了,我说我正在使用 os.listdir() 但想查看它返回的文件夹的内容。

标签: python directory operating-system subdirectory


【解决方案1】:

你应该使用 os.walk() 而不是 litdir() 像 as

import os
import os.path

for dirpath, dirnames, filenames in os.walk("."):
    for file in filenames:
        print(file)

【讨论】:

    【解决方案2】:
    import os
    def getListOfFiles(dirName):
    # create a list of file and sub directories 
    # names in the given directory 
    File_list = os.listdir(dirName)
    Files = list()
    # Iterate over all the entries
    for entry in File_list:
        # Create full path
        fullPath = os.path.join(dirName, entry)
        # If entry is a directory then get the list of files in this directory 
        if os.path.isdir(fullPath):
            Files = Files + getListOfFiles(fullPath)
        else:
            Files.append(fullPath)
                
    return Files
    
    
    #Call the above function to create a list of files in a directory tree i.e.
    dirName = 'C:/Users/huzi95s/Desktop/Django';
    # Get the list of all files in directory tree at given path
    listOfFiles = getListOfFiles(dirName)
    

    【讨论】:

      猜你喜欢
      • 2022-01-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-22
      • 2014-09-19
      • 1970-01-01
      相关资源
      最近更新 更多