为什么我的JSON元素没有从列表中删除?

2024-09-28 01:26:02 发布

您现在位置:Python中文网/ 问答频道 /正文

我想得到第一个元素的变量,并删除它

但是,问题是,即使没有错误,元素仍然没有被删除

Python代码:

import json

with open("listexamp.json") as list:
    b = json.load(list)

    print(b['addresses'][0])
    del b['addresses'][0]

listexamp.json文件:

{"addresses":["addy1", "addy2", "addyn"]}

Tags: 文件代码importjson元素addressesas错误
1条回答
网友
1楼 · 发布于 2024-09-28 01:26:02

因为您要在删除之前打印值:)

正确的代码是

import json

with open("listexamp.json") as l:
    b = json.load(l)

    del b['addresses'][0]
    print(b['addresses'][0])

输出

python test.py
addy2

重写源文件

import json

with open("listexamp.json") as l:
    b = json.load(l)

    del b['addresses'][0]
    print(b['addresses'][0])

with open("listexamp.json", 'w') as l:
    json.dump(b, l)

相关问题 更多 >

    热门问题