IndexError:列表分配索引超出字典范围

时间:2020-01-31 19:18:40

标签: python json dictionary terminal

我正在做一个程序来修改Windows终端的配置文件,这些文件位于JSON文件中。好吧,我想使用python放置另一个配置文件(该配置文件是字典),并且出现以下错误:

Traceback (most recent call last):
  File "C:\Users\DELLNEGRA\Desktop\wtedit.py", line 31, in <module>
    datos["profiles"][len(datos["profiles"])]["guid"] ="{"+pguid+"}"
IndexError: list index out of range

代码是这样的:

import json
import os
import secrets
import numpy as np

path = os.path.dirname(os.path.realpath(__file__))

file = open(path+"/profiles.json","r")
contenido = file.read()
file.close()

datos = json.loads(contenido)

print("Tenes "+str(len(datos["profiles"]))+" consolas registradas.")

print("Añadiendo otra consola...")
pguid = secrets.token_hex(4)+"-"+secrets.token_hex(2)+"-"+secrets.token_hex(2)+"-"+secrets.token_hex(2)+"-"+secrets.token_hex(6)
print("Guid generado: "+pguid)
pname = input("Ingrese el nombre de la consola:")
proot = input("Ingrese la ruta de la consola:")
#datos["profiles"][len(datos["profiles"])] = dict() #Here the error appears
datos["profiles"][len(datos["profiles"])]["guid"] ="{"+pguid+"}"
datos["profiles"][len(datos["profiles"])]["name"] =pname
datos["profiles"][len(datos["profiles"])]["name"] =proot

dumpdatos = json.dumps(datos, sort_keys=True, indent=4)

file = open(path+"/profiles.json","w")
file.write(dumpdatos)
file.close()

如何将字典正确地放在那里?

profiles.json内容:

{
    "$schema": "https://aka.ms/terminal-profiles-schema",
    "defaultProfile": "{0caa0dad-35be-5f56-a8ff-afceeeaa6101}",
    "keybindings": [],
    "profiles": [
        {
            "commandline": "powershell.exe",
            "guid": "{61c54bbd-c2c6-5271-96e7-009a87ff44bf}",
            "hidden": false,
            "name": "Windows PowerShell"
        },
        {
            "commandline": "cmd.exe",
            "guid": "{0caa0dad-35be-5f56-a8ff-afceeeaa6101}",
            "hidden": false,
            "name": "CMD"
        },
        {
            "commandline": "C:\\Users\\DELLNEGRA\\AppData\\Local\\Programs\\Python\\Python37-32\\python.exe",
            "guid": "{0caa0dad-35be-5f56-a8ff-afceeeaa6102}",
            "hidden": false,
            "name": "Python"
        },
        {
            "guid": "{2c4de342-38b7-51cf-b940-2309a097f518}",
            "hidden": false,
            "name": "Ubuntu",
            "source": "Windows.Terminal.Wsl"
        },
        {
            "commandline": "c",
            "guid": "{e78a660a-660b-4d0e-2cc5-35707797c95e}",
            "name": "c"
        }
    ],
    "schemes": []
}

我尝试了datos["profiles"][len(datos["profiles"])].append({"guid":"{"+pguid+"}","name":pname,"commandline":proot}),但是没有用

2 个答案:

答案 0 :(得分:0)

Python规范保证,这将是下标超出范围:

datos["profiles"][len(datos["profiles"])]

或更简单地

my_list[len(my_list)]

Python列表的索引为0。例如,如果您的列表包含5个元素,则合法索引为0..4;没有元素5

相反,尝试

datos["profiles"][-1]

获取最后一个元素。

答案 1 :(得分:0)

如果您要添加新条目到列表末尾,请使用.append

datos["profiles"].append({'guid': ..., 'commandline': ..., 'name': ...})

请注意,您可以在append中一次构造整个对象,而不必一一设置值。