我有一个字典,每次使用用户创建的用户名和密码运行代码时我都会更新。每当我运行脚本时,更新的键和值都会成功出现在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?
答案 0 :(得分:0)
在写入文件时使用附加状态,如:
with open('data.json', 'a') as f:
f.write(json_string)
这将附加字符串,而不是完全替换文件。
答案 1 :(得分:0)
如果您需要更新JSON文件只是为了每次都保存相同的字典,我认为您的代码工作正常。
但是如果你需要一个JSON数组,我会在开头插入“[]”。然后在每次迭代时,您可以删除文件的最后一个字符,插入逗号并序列化该字典。这使您的JSON文件成为有效文件。
也许你考虑过这个案子?
import os
import json
my_dict = {}
file_name = "data.json"
def update_dict():
#update your dictionary here
my_dict["..."] = ...
if __name__ == "__main__":
with open(file_name, 'wb+') as file:
file.write('[]'.encode('utf-8'))
i = 0
#do it N times just for testing
while i < 10:
update_dict()
file.seek(-1, os.SEEK_END)
file.truncate()
json_str = json.dumps(my_dict)
file.write(json_str.encode('utf-8'))
file.write(',]'.encode('utf-8'))
i += 1
file.seek(-2, os.SEEK_END)
file.truncate()
file.write(']'.encode('utf-8'))
file.close()