问题描述
我有一个嵌套字典,其中有一个文件夹列表,像这样一个文件夹, 2013_09_10
是根文件夹:
I have a nested dictionary that has a list of folders, like this one where 2013_09_10
is the root folder:
{'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),打印文件的实际路径
What I' trying to accomplish is, given the name of a file (for example p1.tex), print the actual path of the file
2013_09_10/pieces/p1.tex
我创建了代码,但它只给我所有文件的名称,而不是其父键(directiory):
I've created this piece of code but it only gives me the names of all files, not its parent keys (directiory):
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
我认为我的代码只需要一个简单的修改来完成我想要的,但是我不能排除这个。
I think that my code just need a simple modification to accomplish what I want, but I can't sort this out.
推荐答案
保存路径的前一个目录在第二个参数中,前缀
:
Save the path of the preceding directories in a second argument, prefix
:
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字典中找到一个关键字并返回父母的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!