python - 创建以文件名作为键的目录字典

标签 python python-3.x dictionary tree

我有一个程序只能运行一半,但还不够好。它应该采用一个目录和一个字典,并对字典进行变异,使其具有文件名的键(减去扩展名)和 pygame 图像表面的值(当它是图片时),如果该项目是一个目录,则它的值将是另一个字典,包含该目录的内容。例如,如果我有一棵看起来像这样的树:

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

并且您使用 pics 作为目录并使用空白字典作为字典,您将得到:

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

我的代码如下:

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)

我不认为它在子目录的子目录中循环,因为它通常只是包含我所有图片的目录的空字典。 任何帮助,将不胜感激。谢谢!

最佳答案

问题已上线

if os.path.isdir(item):

您没有添加先前的路径,因此程序不会检查图片中的 other_pics,而是检查 .对于其他_图片

此外,创建路径的更好方法是 os.path.join

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

比设计:

最好不要传递字典并写入它,而是返回它。另外,要检查文件类型,请使用 split,如果您想添加 not-3-chars-long 类型

我的代码:

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)

编辑

刚刚注意到您正在使用“dict”作为变量,小心,它是类型

关于python - 创建以文件名作为键的目录字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48362570/

相关文章:

python - 在 python 中使用 ftplib 时

python - 如何使用另一个词典列表更新词典列表?

python - 多人游戏中的Pygame和socket : OverflowError

javascript - 谷歌地图折线 : Mark the two Polyline coordinates that contain the clicked LatLng

arrays - 如何检查 lua 表是否只包含顺序数字索引?

python - 即使我可以使用凭据进行 SSH,Fabric 也会要求输入密码

python - 如何使用 Python 自动终止使用过多内存的进程?

python - 按字母顺序对文本中出现的字母进行排序

python - 无法在 python 3.6 中将字符串转换为 float

list - 根据元素索引修改列表的元素