添加新对象到 JSON 列表 PYTHON
ADD NEW OBJECT TO JSON LIST PYTHON
我想使用 python 更新 json 中的数组列表 我用过这个
import json
with open('test.json', 'w') as file:
d = {
"name": 'David',
"gender": 'Female'
}
data = json.load(file)
data.append(d)
json.dump(data, file)
和json文件是test.json
[
{
"name": "John",
"gender": "Male"
},
{
"name": "Mary",
"gender": "Female"
}
]
当我 运行 它显示的代码时
Traceback (most recent call last):
File "test.py", line 8, in <module>
data = json.load(file)
File "C:\Users\John\anaconda3\lib\json\__init__.py", line 293, in load
return loads(fp.read(),
io.UnsupportedOperation: not readable
我想要这样的东西,我也尝试过将 w 更改为 r 和 r+
[
{
"name": "John",
"gender": "Male"
},
{
"name": "Mary",
"gender": "Female"
},
{
"name": "David",
"gender": "Female"
}
]
您以w
模式打开了文件,该模式仅用于写入文件。你无法阅读它。此外,该模式将截断文件,丢失旧数据。
使用r+
方式打开读写。然后你需要在读取后返回到文件的开头以覆盖它。你应该调用 truncate()
以防新内容比旧内容短(这可能不会发生在这里,因为你正在追加,但如果文件最初有额外的空白,它可能会发生,最好是安全胜于遗憾)。
with open('test.json', 'r+') as file:
d = {
"name": 'David',
"gender": 'Female'
}
try:
data = json.load(file)
except json.decoder.JSONDecodeError:
# Default to empty list if file is empty
data = []
data.append(d)
file.seek(0)
json.dump(data, file)
file.truncate()
我想使用 python 更新 json 中的数组列表 我用过这个
import json
with open('test.json', 'w') as file:
d = {
"name": 'David',
"gender": 'Female'
}
data = json.load(file)
data.append(d)
json.dump(data, file)
和json文件是test.json
[
{
"name": "John",
"gender": "Male"
},
{
"name": "Mary",
"gender": "Female"
}
]
当我 运行 它显示的代码时
Traceback (most recent call last):
File "test.py", line 8, in <module>
data = json.load(file)
File "C:\Users\John\anaconda3\lib\json\__init__.py", line 293, in load
return loads(fp.read(),
io.UnsupportedOperation: not readable
我想要这样的东西,我也尝试过将 w 更改为 r 和 r+
[
{
"name": "John",
"gender": "Male"
},
{
"name": "Mary",
"gender": "Female"
},
{
"name": "David",
"gender": "Female"
}
]
您以w
模式打开了文件,该模式仅用于写入文件。你无法阅读它。此外,该模式将截断文件,丢失旧数据。
使用r+
方式打开读写。然后你需要在读取后返回到文件的开头以覆盖它。你应该调用 truncate()
以防新内容比旧内容短(这可能不会发生在这里,因为你正在追加,但如果文件最初有额外的空白,它可能会发生,最好是安全胜于遗憾)。
with open('test.json', 'r+') as file:
d = {
"name": 'David',
"gender": 'Female'
}
try:
data = json.load(file)
except json.decoder.JSONDecodeError:
# Default to empty list if file is empty
data = []
data.append(d)
file.seek(0)
json.dump(data, file)
file.truncate()