【问题标题】:How can I make a list of files in a directory where the files in that directory are first before files in subdirectories in python?如何在一个目录中列出文件列表,其中该目录中的文件首先位于python子目录中的文件之前?
【发布时间】:2022-01-17 12:35:33
【问题描述】:

我正在尝试在给定目录中使用递归创建文件列表。我已经能够正确执行此操作,但我的列表顺序不正确。我需要目录最表层上的文件首先显示在列表中,然后子目录中的其他文件按字典顺序排列。

这是我必须执行上面讨论的代码。

import os
important = []
def search_directory(folder):
     hold = os.listdir(folder)
     for i in hold:
          test = os.path.join(folder, i)
          if os.path.isfile(test) == True and 
               os.path.isfile(test) not in interesting:
               interesting.append(test)
          else:
               search_directory(test)
     return important

【问题讨论】:

  • 有什么代码可以分享吗?好像你只是追加到错误的结尾。
  • 刚刚添加了我正在搜索和制作列表的代码,希望对您有所帮助。
  • 你需要改变树遍历。查找 in_order pre_order 和 post_order 遍历。然后,为您提供所需顺序的代码更改对您来说应该很简单。您更改递归调用相对于“if”的位置

标签: python list file directory subdirectory


【解决方案1】:

似乎您需要对目录树进行 BFS 遍历。

import collections
import os

def extract_tree(root):

    q = collections.deque()
    q.append(root)
    
    tree = []
    while q:
        
        root = q.popleft()
        contents = sorted(os.listdir(root))
        for f in contents:
            path = os.path.join(root, f)
            if os.path.isfile(path):
                tree.append(path)
            else:
                q.append(path)
                
    return tree

【讨论】:

    猜你喜欢
    • 2012-09-02
    • 2012-12-09
    • 1970-01-01
    • 1970-01-01
    • 2011-02-23
    • 2023-03-03
    • 1970-01-01
    • 2020-01-29
    相关资源
    最近更新 更多