现有json fi中的Python更新项

2024-05-13 21:46:04 发布

您现在位置:Python中文网/ 问答频道 /正文

我想在我的json文件中更新floatvalues,结构如下:

{"Starbucks": {"Roads": 1.0, "Pyramid Song": 1.0, "Go It Alone": 1.0}}

因此,每当我生成一个已经存在的播放列表时,使用完全相同的项,我就将keyvalues增加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)

但是这个'a'方法会在json后面附加另一个dictionary,并且在以后会产生parsing问题。

同样,如果我使用'w'方法,它将完全覆盖文件。

更新值的最佳解决方案是什么?


Tags: 文件方法pyramidjsongosongit结构
2条回答

您可以在r+模式下打开该文件(同时打开该文件进行读写),读取JSON内容,将seek返回到文件的开头,将其截断,然后将修改后的字典重写回文件:

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)

Appending意味着文件变长了,这既不是JSON的工作原理,也不是JSON的工作原理。

如果要更新某些值,需要加载json文件,请更新值并将其转储回:

with open('pre_database/playlist.json', 'r') as f:
    playlist = json.load(f)
playlist[key] = value  # or whatever
with open('pre_database/playlist.json', 'w') as f:
    json.dump(playlist, f)

另外,您应该在打开文件之前检查文件是否存在,而不是在文件已经打开时:

if os.path.exists('pre_database/playlist.json'):
    with open('pre_database/playlist.json', 'r') as f:
        playlist = json.load(f)
    playlist[key] = value  # or whatever
    with open('pre_database/playlist.json', 'w') as f:
        json.dump(playlist, f)

尽管我猜python的方法是尝试一下,如果文件没有如预期的那样存在,就捕获IOError

根据你继续的方式,最好这样做:

try:
    with open('pre_database/playlist.json', 'r') as f:
        playlist = json.load(f)
except IOError, ValueError:
    playlist = default_playlist

playlist[key] = value  # or whatever

with open('pre_database/playlist.json', 'w') as f:
    json.dump(playlist, f)

罗宾

相关问题 更多 >