学习读取 JSON 文件并用 Python 将 JSON 数据附加到文件中。
在 Python 中,将 JSON 附加到文件包括以下步骤:
dict
或 list
对象中读取 JSON。dict
(或 list
)对象。dict
(或list
)对象写入原始文件。请参阅以下文章以了解如何从文件中读取 JSON 和在 Python 中将 JSON 写入文件。
users.json
文件有一个包含 2 个用户的列表。我们将向其附加第三个用户。
[
{
"Name": "Person_1",
"Age": 11,
"Email": "11@gmail.com"
},
{
"Name": "Person_2",
"Age": 22,
"Email": "22@gmail.com"
}
]
import json
from os import path
filename = 'c:/temp/users.json'
listObj = []
# Check if file exists
if path.isfile(filename) is False:
raise Exception("File not found")
# Read JSON file
with open(filename) as fp:
listObj = json.load(fp)
# Verify existing list
print(listObj)
print(type(listObj))
listObj.append({
"Name": "Person_3",
"Age": 33,
"Email": "33@gmail.com"
})
# Verify updated list
print(listObj)
with open(filename, 'w') as json_file:
json.dump(listObj, json_file,
indent=4,
separators=(',',': '))
print('Successfully appended to the JSON file')
更新后的 JSON 文件为:
[
{
"Name": "Person_1",
"Age": 11,
"Email": "11@gmail.com"
},
{
"Name": "Person_2",
"Age": 22,
"Email": "22@gmail.com"
},
{
"Name": "Person_3",
"Age": 33,
"Email": "33@gmail.com"
}
]
users.json
文件有一个包含 2 个用户的列表。我们将附加一个新属性 role 并修改现有属性 Age。
{
"Name": "Person_1",
"Age": 11,
"Email": "11@gmail.com"
}
import json
from os import path
filename = 'c:/temp/users.json'
dictObj = []
# Check if file exists
if path.isfile(filename) is False:
raise Exception("File not found")
# Read JSON file
with open(filename) as fp:
dictObj = json.load(fp)
# Verify existing dict
print(dictObj)
print(type(dictObj))
dictObj.update({"Age": 12,"Role": "Developer"})
# Verify updated dict
print(dictObj)
with open(filename, 'w') as json_file:
json.dump(dictObj, json_file,
indent=4,
separators=(',',': '))
print('Successfully written to the JSON file')
更新后的 JSON 文件为:
{
"Name": "Person_1",
"Age": 12,
"Email": "11@gmail.com",
"Role": "Developer"
}
如果从 json.load()
方法读取的 JSON 对象是 dict
类型,我们可能会得到这个错误。
第一个示例读取 JSON 列表 [...]
,因此加载的对象的类型为 list
。如果我们正在读取一个包含 JSON 对象 {...}
的文件,那么加载的对象将是 dictionary 类型,上面的代码将给出 AttributeError在调用 list 操作时。
{'Name': 'Person_1', 'Age': 11, 'Email': '11@gmail.com'}
<class 'dict'>
Traceback (most recent call last):
File "C:\temp\temp.py", line 20, in <module>
listObj.append({
AttributeError: 'dict' object has no attribute 'append'
要修复此错误,请注意您从 JSON 文件中读取的 JSON 结构。
快乐学习!!
地址:https://www.cundage.com/article/append-json-to-file.html