【发布时间】:2018-05-18 19:41:44
【问题描述】:
我有一个字典,每次代码运行时都会使用用户创建的用户名和密码进行更新。每当我运行脚本时,更新的键和值都会成功显示在 JSON 文件中。问题是新的字典值和键替换了 JSON 文件的内容,而不是被添加到其中。
my_dict = {}
# there's code here that utilizes the update method for dictionaries to populate #my_dict with a key and value. Due to its length, I'm not posting it.
with open('data.json', 'r') as f:
json_string = json.dumps(my_dict)
json_string
with open('data.json', 'r') as f:
json.loads(json_string)
with open('data.json', 'w') as f:
f.write(json_string)
#these successfully write and save the data to the data.json file. When I run #the script again, however, the new data replaces the old data in my_dict. I #want the new my_dict data to be added instead. How do I do this?
【问题讨论】:
-
你确定要那个吗?如果文件中有多个串联对象,则该文件将不再是有效的 JSON。您必须跳更多圈才能再次阅读它。
-
你需要一个对象数组吗?
-
我需要的是能够遍历 my_dict 并从存储在 data.json 中的 my_dict 条目中获取值