Python递归遍历目录函数超出预期迭代次数问题求助
问题原因分析
- 无全局递归终止标识:你在
update_dir()中匹配到终止目录仅打印了Done,没有设置全局终止标记,此时递归调用栈中还积压了多层未执行完的函数逻辑,会继续向后执行,导致终止后仍反复调用函数。 unzipper()无终止判断:该函数遍历完当前目录内容后,无论是否已经触发终止条件,都会强制调用update_dir(path.dirname(location))向上回溯,会持续触发后续的判断逻辑。- 空间阈值计算错误:原代码中
space *= float(space)*float(0.66)等价于space = space * space * 0.66,和你预期的「取可用空间66%作为终止阈值」逻辑不符,属于笔误。 - 目录访问标记时机滞后:你是在处理完当前目录所有子项后才将目录加入
dirs_visited,递归回溯时容易出现重复判断、重复遍历的问题。
修复后的代码
from os import scandir, path from time import sleep # 全局终止标记 stop_flag = False #Inputs print("解压程序将在解压内容达到可用空间的66%时停止运行。") space = 1 print(f"硬盘可用空间为{space}GB") location = "D:\\64 Test Directory Simple" stop_location = path.dirname(location) # 你的目标终止位置是D:\,这里取一次dirname就够了,原代码取两次结果一致 print(stop_location) #Variables # 修正空间计算逻辑 space = space * 0.66 used_space = 0 last_completed_dir = "" dirs_visited = [] #Functions def update_dir(location_arg): global stop_flag # 已经触发终止就直接返回,不执行任何逻辑 if stop_flag: return location = location_arg print(f" == {location}") print(f" == {stop_location}") if location == stop_location: print("Done!") # 触发终止,设置标记 stop_flag = True return else: unzipper(location) def dirs_visited_func(check_dir): for entry in dirs_visited: if entry == check_dir: return True return False def unzipper(location): global stop_flag if stop_flag: return # 进入目录就标记已访问,避免重复遍历 if dirs_visited_func(location): return dirs_visited.append(location) directory = scandir(location) print(f" --- {location} --- ") sleep(0.25) for entry in directory: if stop_flag: return if entry.is_dir(): if not dirs_visited_func(entry.path): update_dir(entry.path) # 后续补充压缩文件处理逻辑 # 向上回溯前先判断是否已经终止 if not stop_flag: update_dir(path.dirname(location)) unzipper(location)
内容的提问来源于stack exchange,提问作者gaupset
相关产品推荐
相关产品推荐

