【问题标题】:Python - update item in an existing json filePython - 更新现有 json 文件中的项目
【发布时间】:2016-11-10 14:44:35
【问题描述】:

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

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

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

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

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

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

【问题讨论】:

    标签: python json file


    【解决方案1】:

    您可以在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)
    

    【讨论】:

    • @data_garden 可以,但您需要先从文件中读取文件,然后才能将其截断,因此 w 在这里不起作用。您需要手动截断。
    【解决方案2】:

    Appending 表示您的文件越来越长,这既不是您的内容,也不是 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)
    

    虽然我猜pythonic的方法是尝试它并捕获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)
    

    罗宾

    【讨论】:

      【解决方案3】:

      它是追加新字典,因为文件以追加模式打开并且光标位于文件末尾。在将最新的字典转储到文件之前,您需要截断

      with open('pre_database/playlist.json', 'a') as f:
          if os.path.exists('pre_database/playlist.json'):
              f.seek(0)
              playlist = json.load(f)
              #Update your dict here
              playlist.update(dict({'key1':'NewValue1'}))
              f.truncate(0)
              playlist.dump(playlist,f)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-08-11
        • 2015-05-19
        • 2018-09-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-09-05
        • 2020-07-01
        相关资源
        最近更新 更多