1

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}}

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

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])

Output:

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.

tshepang
  • 12,111
  • 21
  • 91
  • 136
Andrés
  • 305
  • 1
  • 4
  • 9
  • your loop invariant is that you will print the filename. Try change it so that it becomes print the directory and then print the rest. – Zeugma Oct 06 '13 at 21:24

1 Answers1

1

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)
unutbu
  • 842,883
  • 184
  • 1,785
  • 1,677