【发布时间】:2020-04-20 05:55:05
【问题描述】:
我试图通过从文本文件中获取内容来修改 JSON 值,但它将值写入 txt 文件的最后一个值。我想要做的是将文本文件中的每一行写为item['ax'] 的值。 (你可以在代码中看到。)
import json, os
with open('res.json', 'r') as file:
json_data = json.load(file)
try:
with open('x.txt', 'r') as file:
line_x = file.read().splitlines()
for xv in line_x:
for item in json_data['resources'][1:]:
item['ax'] = xv
except:
continue
os.chdir('../')
with open('fixed.json', 'w') as out:
json.dump(json_data, out)
这是显示错误结果的屏幕截图:
449 是文本文件中的最后一个值。
【问题讨论】:
-
裸露的
except:子句可能隐藏了一个问题。我强烈建议您避免这样做,并明确列出可能发生的异常(或至少打印或记录发生的异常——即except Exception as exc:,然后在其下方缩进print(exc)。
标签: python arrays json python-3.x