繁体   English   中英

打开 JSON 文件列表并将其存储在另一个列表中

[英]Open and store a list of JSON files in another list

我正在尝试存储一个特定的 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)    

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

在每个 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)   

每次读取文件后,您都会覆盖本地gt2=[]变量。 在迭代list_1循环之前,您应该将其定义为:

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)

暂无
暂无

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

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