簡體   English   中英

如何在一個目錄中列出文件列表,其中該目錄中的文件首先位於 python 中子目錄中的文件之前?

[英]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?

我正在嘗試使用遞歸在給定目錄中創建文件列表。 我已經能夠正確執行此操作,但我的列表順序不正確。 我需要目錄最表層上的文件首先顯示在列表中,然后子目錄中的其他文件按字典順序排列。

這是我必須執行上面討論的代碼。

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

似乎您需要對目錄樹進行 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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM