简体   繁体   English

Python 写入 JSON 文件

[英]Python writing to JSON file

Issue am facing here is that in my code there are many functions which are dumping data in a json file simultaneously like,这里面临的问题是,在我的代码中,有许多函数同时在 json 文件中转储数据,例如,

""" Data of the JSON file is like
   {"Channels": [],1:[],2:[]} """

def update_channels():
 with open(file,'r') as f:
  data = json.load(f)
 data["Channels"].append(stuff)
 with open(file,'w') as f:
  json.dump(data,f)

def update_key(key_no):
 with open(file,'r') as f:
  data = json.load(f)
 data[key_no].append(stuff)
 with open(file,'w') as f:
  json.dump(data,f)

These update functions are triggered by events and there can be cases where they are executed at the same time or within no time gap so, data of that JSON file can be overlapped causing loss of data.这些更新函数由事件触发,可能会同时执行或在没有时间间隔内执行,因此 JSON 文件的数据可能会重叠,从而导致数据丢失。

How can I resolve this problem?我该如何解决这个问题? Basically, this is for a discord bot and these functions will be triggered by discord events.基本上,这是针对 discord 机器人的,这些功能将由 discord 事件触发。

Thanks!谢谢!

There are several ways to do this.有几种方法可以做到这一点。 One is to use a database, which will do access control for you.一种是使用数据库,它将为您进行访问控制。 Another one is to use a lock.另一种是使用锁。 But the simplest one is to leave it to the kernel: write to a temporary file, then replace the original atomically.但最简单的方法是将其留给 kernel:写入一个临时文件,然后原子地替换原始文件。 Ie to write a file, do this instead:即写一个文件,而不是这样做:

from tempfile import NamedTemporaryFile
import os

dirname = os.dirname(file)
with NamedTemporaryFile(dir=dirname, delete=False) as temp:
    json.dump(data, temp)
    temp.close()
    os.replace(temp.name, file)

Python guarantees that nothing will interrupt os.replace . Python 保证不会中断os.replace

EDIT: This merely answers the question as posed;编辑:这只是回答提出的问题; but I fully agree with comments saying a database is the right choice.但我完全同意关于数据库是正确选择的评论。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM