我想使用我已经使用过的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"
}
]
答案 0 :(得分:1)
您已经以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()