Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/346.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/json/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 在不重写现有json文件的情况下向其添加值_Python_Json - Fatal编程技术网

Python 在不重写现有json文件的情况下向其添加值

Python 在不重写现有json文件的情况下向其添加值,python,json,Python,Json,JSON文件中的字典如下所示: { 'key1':value1 'key2':value2 } { 'key1':value1 'key2':value2 'key3':value3 } with open(path, 'rb+') as f: s = f.read() index = s.rfind('}') f.seek(index) f.write(',\n[YOUR JSON HERE]\n') f.write(s[index:]) 我正在编

JSON文件中的字典如下所示:

{
'key1':value1
'key2':value2
}
{
'key1':value1
'key2':value2
'key3':value3
}
with open(path, 'rb+') as f:
    s = f.read()
    index = s.rfind('}')
    f.seek(index)
    f.write(',\n[YOUR JSON HERE]\n')
    f.write(s[index:])
我正在编写一个循环,其中每次迭代都会向文件中的字典添加一个新键。例如,在一次迭代后,文件中的字典如下所示:

{
'key1':value1
'key2':value2
}
{
'key1':value1
'key2':value2
'key3':value3
}
with open(path, 'rb+') as f:
    s = f.read()
    index = s.rfind('}')
    f.seek(index)
    f.write(',\n[YOUR JSON HERE]\n')
    f.write(s[index:])

我想使用一种方法将一个新键直接附加到文件中的字典中。我不想把文件读入,更改数据,然后再写出来。有没有办法做到这一点

这是一个相当粗糙的实现,它假设文件以}和换行符结尾(这解释了-2):


您可以通过找到最后一个闭合大括号,然后使用
file.seek
转到该位置来完成此操作。然后您可以编写新值,如下所示:

{
'key1':value1
'key2':value2
}
{
'key1':value1
'key2':value2
'key3':value3
}
with open(path, 'rb+') as f:
    s = f.read()
    index = s.rfind('}')
    f.seek(index)
    f.write(',\n[YOUR JSON HERE]\n')
    f.write(s[index:])

请注意,如果您的结构实际上首先是一个列表,则需要您使用
]
,否则应该是相同的。还请注意,根据您是否通常使用尾随逗号(即
{a:1,b:13,c:231,}
),您可能希望使用我在第一个
write
命令中添加的逗号。

是否有避免重写该文件的原因?如果这是一个小json文件,并且该操作将不太频繁,重写文件就行了。如果文件很大和/或频繁读写,请使用其他工具,例如数据库。