虽然我认为Martijn Pieters在他的回答中解决了主要问题(你需要从递归案例中返回),但我不认为他建议的代码能够正常工作。
您正在尝试对rqfile嵌套dictionary字典中的值实施深度优先搜索。但是您当前的代码无法正确处理递归情况。如果在其中一个递归调用中找到结果,或者如果递归调用未能找到目标,则需要做出相应的响应。
这是我认为你需要的东西,为了清楚起见,重命名或重新安排了一些东西:def get_path(directory, rqfile, prefix=[]):
for filename, value in directory.items():
path_list = prefix + [filename]
if not isinstance(value, dict): # base case
path = os.path.join(*path_list)
if rqfile in path: # Found the file. Do you want to do something
return path # with the value here, or is it junk?
else: # recursive case
try:
return get_path(value, rqfile, path_list) # this only returns if
except ValueError: # the recursion doesn't raise
pass
raise ValueError("Requested file not found") # not found here or in children
用法示例:>>> directory = {"a": "a info",
"b": {"c": "b/c info", "d": "b/d info"},
"e": {"f": "e/f info", "g": {"h": "e/g/h info"}}}>>> print(get_path(directory, "h"))e\g\h>>> print(get_path(directory, r'g\h'))e\g\h
如果你不想在找不到文件时引发异常,你也可以返回一个sentinel值,就像None代替最后一行一样,并在递归的情况下检查它的sentinel值而不是try/ except:result = get_path(value, rqfile, path)
if result is not None:
return result