Python迭代目录并更新字典

时间:2016-02-02 00:24:54

标签: python for-loop dictionary nested-loops

字典" d"当我想要添加所有文件夹时,仅包含最新的迭代子文件夹键和值。我不知道为什么我的字典会在文件夹更改后从空字典开始更新。

import os
from os.path import join

for (dirname, dirs, files) in os.walk('.'):
    d = dict()
    for filename in files:
        if filename.endswith('.txt') :
            value_thefile = os.path.join(dirname,filename)
            key_size = os.path.getsize(value_thefile)
            d.update({key_size:value_thefile})
print d

1 个答案:

答案 0 :(得分:0)

字典d一直设置为外部for循环的每次迭代的新空字典。即它不断重新初始化为{}

for (dirname, dirs, files) in os.walk('.'):
    d = dict()    # this makes d == {} for each iteration of os.walk('.')
    for filename in files:
        ...

相反,在循环之外初始化它,如下所示:

d = dict()    # this makes d == {} only at the start
for (dirname, dirs, files) in os.walk('.'):
    for filename in files:
        ...  # rest of your code