更新Python中的JSON文件

tquggr8v  于 2023-05-23  发布在  Python
关注(0)|答案(4)|浏览(111)

我想更新的.json文件具有以下结构:

{
  "username": "abc",
  "statistics": [
    {
      "followers": 1234,
      "date": "2018-02-06 02:00:00",
      "num_of_posts": 123,
      "following": 123
    }
  ]
}

我想让它插入一个新的统计数据

{
  "username": "abc",
  "statistics": [
    {
      "followers": 1234,
      "date": "2018-02-06 02:00:00",
      "num_of_posts": 123,
      "following": 123
    },
    {
      "followers": 2345,
      "date": "2018-02-06 02:10:00",
      "num_of_posts": 234,
      "following": 234
    }
  ]
}

with open(filepath, 'w') as fp:
    json.dump(information, fp, indent=2)

该文件将总是被覆盖。但是我想把统计的项目加进去。我尝试了许多可能的方式阅读文件,并在之后追加它,但它从来没有工作。
数据将写入信息变量中,就像

information = {
  "username": username,
  "statistics": [
      {
          "date": datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
          "num_of_posts": num_of_posts,
          "followers": followers,
          "following": following
      }
  ]
}

那么,我如何更新.json文件,我的信息被正确添加?

cnwbcb6i

cnwbcb6i1#

您可能希望沿着以下操作:

def append_statistics(filepath, num_of_posts, followers, following):

    with open(filepath, 'r') as fp:
        information = json.load(fp)

    information["statistics"].append({
        "date": datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
        "num_of_posts": num_of_posts,
        "followers": followers,
        "following": following
    })

    with open(filepath, 'w') as fp:
        json.dump(information, fp, indent=2)
9wbgstp7

9wbgstp72#

您需要读取.json文件,然后追加新的数据集并转储该数据。查看代码。

import json
appending_statistics_data = {}

appending_statistics_data["followers"] =  2346
appending_statistics_data["date"] = "2018-02-06 02:10:00"
appending_statistics_data["num_of_posts"] =  234
appending_statistics_data["following"] = 234

with open(file.json, 'r') as fp:
    data = json.load(fp)

data['statistics'].append(appending_statistics_data)    
#print(json.dumps(data,indent=4))               

with open(file.json, 'w') as fp:
    json.dump(data, fp, indent=2)
kh212irz

kh212irz3#

你可以使用这个函数:

def append_statistics(filepath, num_of_posts, followers, following):
    new_statistics_record={
        "date": datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
        "num_of_posts": num_of_posts,
        "followers": followers,
        "following": following
    }

    with open(filepath, 'r') as fp:
        information = json.load(fp)

    information["statistics"].append(new_statistics_record)

    with open(filepath, 'w') as fp:
        json.dump(information, fp, indent=2)
kjthegm6

kjthegm64#

通常情况下,您不会直接更新正在阅读的文件。
您可以考虑:
1.从源文件读取。
1.做处理
1.写入新的临时文件
1.关闭源文件和临时文件
1.将临时文件重命名(移动)回源文件

相关问题