我有一个名为weapons.json
的.json文件:
{
"weapons": [
{
"game": "EMPTY",
"weapon": "EMPTY",
"down": "0",
"up": "0",
"left": "0",
"right": "0"
},
{
"game": "DELETE",
"weapon": "DELETE",
"down": "0",
"up": "0",
"left": "0",
"right": "0"
}
]
}
此数据仅用于测试
我想从该文件中删除第二项:
{
"game": "DELETE",
"weapon": "DELETE",
"down": "0",
"up": "0",
"left": "0",
"right": "0"
}
为此,我尝试了以下功能:
#Deleting json info from the selected weapon
def deleteWeapon():
with open('json/weapons.json') as info:
weapons_dict = json.load(info)
for weapon in weapons_dict['weapons']:
if (weapon['game']=="DELETE" and weapon['weapon']=="DELETE" and weapon['down']=="0" and weapon['up']=="0" and weapon['left']=="0" and weapon['right']=="0"):
del weapon
with open('json/weapons.json','w') as remove:
json.dump(weapons_dict,remove,indent=2)
deleteWeapon()
其中我尝试执行del weapon
删除该值,但这不起作用。我也试过做del weapon['XXX'] del weapon['XXX']
使用所有项值,但执行此操作时.json如下所示
{
"weapons": [
{
"game": "EMPTY",
"weapon": "EMPTY",
"down": "0",
"up": "0",
"left": "0",
"right": "0"
},
{}
]
}
而不是:
{
"weapons": [
{
"game": "EMPTY",
"weapon": "EMPTY",
"down": "0",
"up": "0",
"left": "0",
"right": "0"
}
]
}
我很高兴听到任何帮助
试试这个:
使用
i
作为当前索引在列表上迭代,然后在需要删除该武器时调用del weapons_dict["weapons"][i]
已经找到了解决方案
代码应该如下所示:
相关问题 更多 >
编程相关推荐