本文介绍了将值添加到现有的json文件中,而无需重写它的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在JSON文件中的字典如下:
My dictionary in a JSON file looks like this:
{
'key1':value1
'key2':value2
}
我正在编写一个循环,其中每次迭代都会向文件中的字典添加新键.例如,经过一轮迭代后,文件中的字典如下所示:
I'm writing a loop where each iteration adds a new key to the dictionary in the file. For example, after one iteration the dictionary in the file looks like this:
{
'key1':value1
'key2':value2
'key3':value3
}
我想使用一种方法将新密钥直接附加到文件中的字典中.我不想读文件,更改数据并再次写回.有什么办法吗?
I want to use a method to directly append a new key into the dictionary in the file. I don't want to have to read the file in, change data and write it back out again. Is there any way to do this?
推荐答案
这是一个非常粗略的实现,它假定文件以}和换行符结尾(解释-2):
This is a rather crude implementation that assumes that the file ends with } and a newline (which explains the -2):
with open('data.json','rb+') as f:
f.seek(-2,2)
f.write(b"'new_key':new_value\n}\n")
这篇关于将值添加到现有的json文件中,而无需重写它的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!