我想更新float values我的json文件,结构如下:
{"Starbucks": {"Roads": 1.0, "Pyramid Song": 1.0, "Go It Alone": 1.0}}
Run Code Online (Sandbox Code Playgroud)
因此,每当我生成一个已经存在的播放列表(具有完全相同的项目)时,我都会增加key values+ 1.0。
我有一个使用'append'选项打开的文件
with open('pre_database/playlist.json', 'a') as f:
if os.path.exists('pre_database/playlist.json'):
#update json here
json.dump(playlist,f)
Run Code Online (Sandbox Code Playgroud)
但这种'a'方法会向 追加另一个方法dictionary,并且稍后json会产生问题。parsing
同样,如果我使用'w'方法,它会完全覆盖该文件。
更新值的最佳解决方案是什么?
您可以在模式下打开文件r+(打开文件进行读写),读入 JSON 内容,返回到文件的开头,截断它,然后将修改后的字典重写回文件:
if os.path.exists('pre_database/playlist.json'):
with open('pre_database/playlist.json', 'r+') as f:
playlist = json.load(f)
# update json here
f.seek(0)
f.truncate()
json.dump(playlist, f)
Run Code Online (Sandbox Code Playgroud)