gpt4 book ai didi

python - 在 Python 中更新 JSON 文件

转载 作者:行者123 更新时间:2023-11-30 22:21:30 25 4
gpt4 key购买 nike

我想要更新的 .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 文件以正确添加我的信息?

最佳答案

您可能想做一些类似的事情:

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)

关于python - 在 Python 中更新 JSON 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48634389/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com