Michael
Michael

Reputation: 426

create dictionary of directory with filenames as keys

I have a program that half works, and that is not good enough. it is supposed to take a directory and a dictionary and mutate the dictionary to have keys of the filename (minus the extension) and values of the pygame image surface when it is a picture, and if the item is a directory, it's value will be another dictionary, containing the contents of that directory. for example if i have a tree that looks like this:

pics +  
     |  
    pic1.png  
     |  
    pic2.png 
     |
     other_pics 
        +-  
          pic1.png
          |
          pic2.png

and you used pics as your directory and a blank dictionary as dictionary, you would get:

{'pic1': <Surface object etc...>
  'pic2': <Surface object etc...>
  'other_pics': {
    'pic1': <Surface object etc...>
    'pic2': <Surface object etc...>
}}

my code is below:

from pygame.image import load
import os

def gather_pics(dictionary, dir='.'):

    print(dir)

    for item in os.listdir(dir):
        if os.path.isdir(item):
            dictionary[item] = {}
            gather_pics(dictionary[item], '{}{}{}'.format(dir, '\\' if os.name == 'nt' else '/', item))

        elif item[-4:] in ('.png', '.jpg'):
            dictionary[item.split('.')[0]] = load('{}{}{}'.format(dir, '\\' if os.name == 'nt' else '/', item))

if __name__ == '__main__':
    dict = {}
    gather_pics(dict)
    print(dict)

i dont think it is cycling through the sub-directories' sub-directories because it often just turns out an empty dict for the directory with all my pictures. any help would be appreciated. thanks!

Upvotes: 1

Views: 1994

Answers (1)

Mysak0CZ
Mysak0CZ

Reputation: 964

The problem is on line

if os.path.isdir(item):

You don't add pervious path, so instead of checking pics for other_pics, the program checks . for other_pics

Also, much nicer way to create path is os.path.join

if os.path.isdir(os.path.join(dir, item)):

Than to design:

It may be better not to pass dictionary and write to it, but return it insted. Also to check type of file, use split, if you will want to add not-3-chars-long type

My code:

from pygame.image import load
import os

def gather_pics(dir='.'):

    dictionary = {}

    print(dir)

    for item in os.listdir(dir):
        if os.path.isdir(os.path.join(dir, item)):
            dictionary[item] = gather_pics(os.path.join(dir, item))

        elif item.split(".")[-1] in ('png', 'jpg'):
            dictionary[item.split('.')[0]] = load(os.path.join(dir, item))

    return dictionary

if __name__ == '__main__':
    dict = gather_pics()
    print(dict)

EDIT

Just noticed you are using "dict" as variable, careful, it is type

Upvotes: 1

Related Questions