簡體   English   中英

遞歸 function 以返回 Python 中的字典

[英]Recursive function to return a dictionary in Python

我有上面的樹。 我需要以遞歸方式搜索樹中的目錄和文件,並將它們作為字典以下列形式返回 - >鍵:目錄/文件名和值:文件的第一行

eg: key:1/2/5/test5    value:first line of test 5

在此處輸入圖像描述

到目前為止,我創建了下一個代碼:

def search(root):
    items = os.listdir(root)
    
    for element in items:
        if os.path.isfile(element):
        
            with open (element) as file:
                one_line=file.readline()
                print(one_line)

        elif os.path.isdir(element):
            search(os.path.join(root,element))

問題是我的代碼只搜索目錄。 請讓我明白我錯在哪里以及如何解決它。 非常感謝任何幫助,謝謝!

你可以使用os.walk

以下 function 將不包括空文件夾。

def get_tree(startpath):
    tree = {}
    for root, dirs, files in os.walk(startpath):
        for file in files:
            path = root+"/"+file
            with open(path,'r') as f:
                first_line =  f.readline()
            tree[path] = first_line
    return tree

output 將是這樣的:

{
    file_path : first_line_of_the_file,
    file_path2 : first_line_of_the_file2,
    ...
}

您的代碼幾乎是正確的。 不過,它必須稍微調整一下。 進一步來說,

  1. element是文件或目錄名稱(不是路徑)。 如果它是子目錄或子目錄中的文件, if os.path.isfile(element)elif os.path.isdir(element)的值將始終為False 因此,分別用if os.path.isfile(os.path.join(root, element))elif os.path.isdir(os.path.join(root, element))替換它們。

  2. 同樣, with open(element)應該替換為with open(os.path.join(root,element))

  3. 讀取文件的第一行時,您必須將路徑和該行存儲在字典中。

  4. elif os.path.isdir(element)中調用遞歸 function 時,必須更新該字典。

請參閱下面的完整片段:

import os

def search(root):

    my_dict = {}   # this is the final dictionary to be populated

    for element in os.listdir(root):
        
        if os.path.isfile(os.path.join(root, element)):
            try: 
                with open(os.path.join(root, element)) as file:
                    my_dict[os.path.join(root, element)] = file.readline() # populate the dictionary
            except UnicodeDecodeError: 
                # This exception handling has been put here to ignore decode errors (some files cannot be read)
                pass

        elif os.path.isdir(os.path.join(root, element)):
            my_dict.update(search(os.path.join(root,element)))  # update the current dictionary with the one resulting from the recursive call

    return my_dict

print(search('.'))

它打印如下字典:

{
 "path/file.csv": "name,surname,grade",
 "path/to/file1.txt": "this is the first line of file 1",
 "path/to/file2.py": "import os"
}

為了可讀性, os.path.join(root, element)可以存儲在一個變量中,然后:

import os

def search(root):

    my_dict = {}   # this is the final dictionary to be populated

    for element in os.listdir(root):
        path = os.path.join(root, element)

        if os.path.isfile(path):
            with open(path) as file:
                my_dict[path] = file.readline()

        elif os.path.isdir(path):
            my_dict.update(search(path))

    return my_dict

print(search('.'))

暫無
暫無

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

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