[Python] How to generate a directory tree iteratively, implemented in Python?

Discussão em 'Python' iniciado por Stack, Novembro 22, 2024.

  1. Stack

    Stack Membro Participativo

    I have already implemented generating a directory tree using recursion:

    import os
    import re
    import hashlib

    PIPE = "│"
    ELBOW = "└──"
    TEE = "├──"
    PIPE_PREFIX = "│ "
    SPACE_PREFIX = " "

    root_dir = ""
    tree = []

    def extract_number(file_name):
    match = re.search(r"\d+", file_name)
    return int(match.group()) if match else float("inf")

    def get_md5(file_path):
    hasher = hashlib.md5()
    with open(file_path, "rb") as f:
    for chunk in iter(lambda: f.read(8192), b""):
    hasher.update(chunk)
    return hasher.hexdigest()

    def tree_head():
    tree.append(f"{root_dir}{os.sep}")
    tree.append(PIPE)

    def get_entries(directory):
    with os.scandir(directory) as entries:
    entries = list(entries)

    entries = [entry for entry in entries if entry.name != ".DS_Store"]

    entries = sorted(entries, key = lambda entry: (entry.is_file(), extract_number(entry.name)))

    return entries

    def tree_body(directory, prefix = ""):
    entries = get_entries(directory)
    entries_count = len(entries)
    for index, entry in enumerate(entries):
    connector = ELBOW if index == entries_count - 1 else TEE
    if entry.is_dir():
    add_directory(entry, index, entries_count, prefix, connector)
    else:
    add_file(entry, prefix, connector)

    def add_directory(directory, index, entries_count, prefix, connector):
    tree.append(f"{prefix}{connector} {directory.name}{os.sep}")

    if index != entries_count - 1:
    prefix += PIPE_PREFIX
    else:
    prefix += SPACE_PREFIX

    tree_body(directory, prefix)

    def add_file(file, prefix, connector):
    md5_hash = get_md5(file)
    tree.append(f"{prefix}{connector} {file.name} -> {md5_hash}")

    def build_tree():
    tree_head()
    tree_body(root_dir)
    return tree

    def generate():
    tree = build_tree()

    for entry in tree:
    print(entry)

    generate()


    This code generates a directory tree with file and directory names, as well as their MD5 hashes. Here's an example of the output that this script might produce, assuming the specified directory structure:

    root_dir
    │
    ├── folder1/
    │ ├── file1.txt -> d41d8cd98f00b204e9800998ecf8427e
    │ └── file2.txt -> 098f6bcd4621d373cade4e832627b4f6
    └── folder2/
    ├── file3.txt -> 6dcd4ce23d88e2ee9568ba546c007c63
    └── file4.txt -> d41d8cd98f00b204e9800998ecf8427e


    How can the tree_body() function be converted from a recursive implementation to an iterative one? I have tried many methods and found it difficult to print in the correct order. I don't know what the correct approach for designing the algorithm for this problem looks like.

    Continue reading...

Compartilhe esta Página