我有一些带有一些数据的json文件,并且偶尔会更新这个文件.
我读了这个文件:
with open('index.json', 'rb') as f:
idx = json.load(f)
Run Code Online (Sandbox Code Playgroud)
然后检查是否存在来自潜在新数据的密钥,如果密钥不存在则更新文件:
with open('index.json', mode='a+') as f:
json.dump(new_data, f, indent=4)
Run Code Online (Sandbox Code Playgroud)
但是,此过程只是创建新的json对象(python dict)并将其作为新对象追加到输出json文件中,使文件无效json文件.
有没有简单的方法将新数据附加到json文件而不覆盖整个文件,通过更新初始字典?
kgr*_*kgr 11
执行所需操作的一种方法是在文件中每行写一个JSON对象.我正在使用这种方法,它运作良好.
一个很好的好处是,您可以更有效地读取文件(内存方式),因为您可以一次读取一行.如果你需要所有这些,在Python中组装列表没有问题,但如果你不这样做,你运行得更快,你也可以追加.
所以最初编写所有对象,你会做这样的事情:
with open(json_file_path, "w") as json_file:
for data in data_iterable:
json_file.write("{}\n".format(json.dumps(data)))
Run Code Online (Sandbox Code Playgroud)
然后有效读取(无论文件大小如何,都会消耗很少的内存):
with open(json_file_path, "r") as json_file:
for line in json_file:
data = json.loads(line)
process_data(data)
Run Code Online (Sandbox Code Playgroud)
更新/追加:
with open(json_file_path, "a") as json_file:
json_file.write("{}\n".format(json.dumps(new_data)))
Run Code Online (Sandbox Code Playgroud)
希望这可以帮助 :)