簡體   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