python - 打开 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)
我猜在每次迭代中它都会被替换但不确定。
解决方案
在每个 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)
推荐阅读
- javascript - Google Apps 脚本 JQuery 表单
- python - 如何从包含的对象调用容器类方法?
- c++ - Cpp 文件说 [converted] 并且是一堆随机字符
- ruby-on-rails - 在开发日志中静音资产请求(config.assets.quiet = true 不起作用)
- python - 网页抓取错误,它说索引不足,怎么回事
- matlab - 在 MATLAB 中高效生成置换矩阵
- python - 使用 tf.data 和叉积对两个数据集进行增强
- r - 按组查找某个值后的第一个非 NA 值
- html - 如果项目内的内容可以将其扩展超出其分配范围,那么 CSS Grid 中的 fr 单位有什么意义
- cordova - Ionic 4:让应用程序在后台保持活力