简体   繁体   English

Python:使用字典进行文件搜索

[英]Python: file search using dictionary

I have written a small script to find a file in directories and sub-directories.我编写了一个小脚本来在目录和子目录中查找文件。 I placed these in dictionaries and sub dictionaries within the root dictionary.我将它们放在根词典中的词典和子词典中。

So I am trying to find a file within the dictionary of files and sub directories.所以我试图在文件和子目录的字典中找到一个文件。 I am trying to print out contents of this dictionary first then I will be able to modify the code to look for the file within the dictionary.我试图先打印出这本字典的内容,然后我将能够修改代码以在字典中查找文件。

Here is the code:这是代码:

def recurdd(db):
    for key in db:
        for item in db[key]:
            if hasattr(item,'append'):
                recurdd(item)
            else:
                print key,'=>',db[key]
                print

This code prints out the same dictionary all the time which I want to correct.这段代码一直打印出我想要更正的同一个字典。 So if I have a dictionary, ie:所以如果我有一本字典,即:

d = {'a': [{'b': [1, 2, 3]}, {'c': [55, 12, 32]}, 1, 2]}

Please assist me with this issue.请帮助我解决这个问题。

Thanks谢谢

The correct code would be:正确的代码是:

def recurse_directory(dictionary):
    for dirname, dir_content in dictionary.iteritems():
        for filename in dir_content:
            if type(filename) == dict: # It's a directory
                recurse_directory(filename)
            else:
                print "{} => {}".format(dirname, filename)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM