我要更新的.json文件具有以下结构:
%file was unexpected at this time.
我希望它插入一个像这样的新统计数据
{
"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)
那么如何更新我的信息正确添加的.json文件?
答案 0 :(得分:3)
您可能希望按照以下方式执行以下操作:
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)
答案 1 :(得分:0)
您需要阅读.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)
答案 2 :(得分:-1)
通常情况下,您不能直接更新您正在阅读的文件。
您可以考虑: