首页 > 解决方案 > 打开 JSON 文件列表并将其存储在另一个列表中

问题描述

我正在尝试存储一个特定的 JSON 文件,该文件位于根文件夹的每个子文件夹中。

我设法做到了,现在我有了这个清单:

list_1

这使:

['C:\\Users\\user\\Downloads\\problem00001\\ground-truth.json',
 'C:\\Users\\user\\Downloads\\problem00002\\ground-truth.json',
 'C:\\Users\\user\\Downloads\\problem00003\\ground-truth.json']

现在我试图JSON在一个列表中打开这些文件中的每一个,但只存储最后一个文件。目标是将它们全部存储在一起,而不仅仅是最后一个。

这是我尝试过的:

for k in list_1:
    with open(k, 'r') as f:
        gt = {}
        gt2=[]
        for i in json.load(f)['ground_truth']:
            #print(i) <--- This here prints exactly what I need
            gt[i['unknown-text']] = i['true-author']
        gt2.append(gt)    

我猜在每次迭代中它都会被替换但不确定。

标签: pythonjsonfor-loop

解决方案


在每个 for 循环中重新初始化 gt2 列表。因此它应该在循环之外。

gt2=[]
for k in list_1:
    with open(k, 'r') as f:
        gt = {}
        for i in json.load(f)['ground_truth']:
            #print(i) <--- This here prints exactly what I need
            gt[i['unknown-text']] = i['true-author']
        gt2.append(gt)   

推荐阅读