我有一个嵌套字典,其中包含一个文件夹列表,例如其中 2013_09_10
是根文件夹:
{'2013_09_10': {'master.tex': None, 'master.log': None, 'master.pdf': None, 'Makefile': None, 'pieces': {'rastin.tex': None, '02 Human Information Processing.txt': None, 'p1.tex': None, 'p3.tex': None, '03 Models and Metaphors.txt': None, 'p2.tex': None}, 'master.aux': None, 'front_matter.tex': None}}
我想要完成的是,给定文件名(例如 p1.tex),打印文件的实际路径
2013_09_10/pieces/p1.tex
我已经创建了这段代码,但它只提供了所有文件的名称,而不是其父键(目录):
def get_files(directory):
for filename in directory.keys():
if not isinstance(directory[filename], dict):
print filename
else:
get_files(directory[filename])
输出:
master.tex
master.log
master.pdf
Makefile
rastin.tex
02 Human Information Processing.txt
p1.tex
p3.tex
03 Models and Metaphors.txt
p2.tex
master.aux
front_matter.tex
我认为我的代码只需要进行简单的修改即可完成我想要的,但我无法解决这个问题。
最佳答案
将前面目录的路径保存在第二个参数中,前缀
:
import os
def get_files(directory, prefix=[]):
for filename in directory.keys():
path = prefix+[filename]
if not isinstance(directory[filename], dict):
print os.path.join(*path)
else:
get_files(directory[filename], path)
关于python - 在 python 字典中查找键并返回其父项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19214099/