我想创建一个程序来加载json文件,读取该文件,然后添加一个 反对列表。
import json
newo = {
"balance": "1234",
"time": "forever"
}
with open("json.json", "r") as f:
data = json.load(f)
with open("json.json", "w") as f:
json.dump(newo, f)
这是我一直在使用的python文件。
{
"cointiply": [
{
"balance" : "242537",
"time": "28.05.2019"
},
{
"balance": "246362",
"time": "29.05.2019"
}
]
}
那是json文件。
我现在希望将newo列表“ cointiply”插入json列表中。
有什么想法可以做到吗? 因为现在“ newo”列表正在删除json文件中的所有内容,然后才插入,就像文件将为空一样。
答案 0 :(得分:2)
使用list.append
例如:
import json
newo = {
"balance": "1234",
"time": "forever"
}
with open("json.json", "r") as f:
data = json.load(f)
data["cointiply"].append(newo) #Append newo
with open("json.json", "w") as f:
json.dump(data, f)
答案 1 :(得分:1)
您可以尝试:
>>> demo = {
... "cointiply": [
... {
... "balance" : "242537",
... "time": "28.05.2019"
... },
... {
... "balance": "246362",
... "time": "29.05.2019"
... }
... ]
... }
>>> newo = {
... "balance": "1234",
... "time": "forever"
... }
>>> demo["cointiply"].append(newo)
>>> demo
{'cointiply': [{'balance': '242537', 'time': '28.05.2019'}, {'balance': '246362', 'time': '29.05.2019'}, {'balance': '1234', 'time': 'forever'}]}
答案 2 :(得分:0)
您可以使用一个临时文件,向其中写入新数据,然后替换两个文件,而不必两次打开同一文件。关于列表-您需要使用append
才能将新数据添加到cointiply
元素中:
from os import remove
from shutil import move
from tempfile import mkstemp
newo = {
"balance": "1234",
"time": "forever"
}
fh, abs_path = mkstemp()
file_path = "json.json"
with open(fh, "w") as newf, open(file_path, "r") as oldf:
data = json.load(oldf)
data["cointiply"].append(newo)
json.dump(data, newf)
# Remove original file
remove(file_path)
# Move new file
move(abs_path, file_path)