我想通过python3将数据添加到我的data.js文件中。有人有什么想法吗? data.js文件如下所示:

{
    "data":[
        {"Name": "Bob", "Age": "21"},
        {"Name": "Monty", "Age": "15"}
    ]
}


到目前为止,在python中我有:

import json
name = input("Name: ")
age = input("Age: ")
data = {
    "Name": name,
    "Age": age,
}

with open("data.js", "w") as file:
    json.dump([data], f)


但这另存为[{"Name": "Bob", "Age": "23"}]

有人有建议吗?

最佳答案

您可以读入现有文件并追加新数据:

import json

with open('data.js') as f:
    content = json.load(f)

name = input("Name: ")
age = input("Age: ")

person = {"name": name, "Age": age} #Build object for new person ...
content['data'].append(person) # .. and append it to your existing 'data'

with open("data.js", "w") as file:
    json.dump(content, f)

关于python - 如何从html和或python3向js文件添加/添加数据,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/35435115/

10-14 00:01