有一个代码
import json
up = 5
with open("test.json", "w") as write_file:
json.dump(up, write_file)
它将 up 变量的值写入 test.json 文件。但是您可以看到 test.json 文件在执行该行期间被重置为零(= 0 字节):
with open("test.json", "w") as write_file:
通过在转储命令之前添加延迟可以更清楚地看到这一点:
import json
import time
up = 5
with open("test.json", "w") as write_file:
time.sleep(1)
json.dump(up, write_file)
这是正常的,因为在归零后会写入新数据。但
那么,当程序崩溃时,就可能会丢失json文件的内容
是否有任何标准和不那么标准的方法来避免这种情况?