我已经实现了使用递归生成目录树:
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()
此代码生成一个目录树,其中包含文件和目录名称及其 MD5 哈希值。以下是该脚本可能产生的输出示例(假设指定的目录结构):
root_dir
│
├── folder1/
│ ├── file1.txt -> d41d8cd98f00b204e9800998ecf8427e
│ └── file2.txt -> 098f6bcd4621d373cade4e832627b4f6
└── folder2/
├── file3.txt -> 6dcd4ce23d88e2ee9568ba546c007c63
└── file4.txt -> d41d8cd98f00b204e9800998ecf8427e
tree_body()
函数如何从递归实现转换为迭代实现?
我尝试了很多方法,发现很难按照正确的顺序打印。
我不知道为这个问题设计算法的正确方法是什么样的。
尝试使用目录类作为字典,例如(伪代码):
Class DirBody():
def __init__(self, name, depth):
self.name = name
self.depth = depth
self.childDir = []
self.childFile = []
def __str__(self):
self.printDirs()
self.printFiles()
def printDirs(self):
pass
def printFiles(self):
pass
你可以步行