在python中写入XML文件时,为什么会出现子索引超出范围的错误?

我可以修理吗

我正在尝试在XML文件的字典列表中写一个名称,但是我将IndexError作为子索引超出范围。我是XML文件的新手。这是我的代码

import os
import xml.etree.ElementTree as ET
from xml.etree.ElementTree import Element, SubElement, Comment, tostring
from xml.dom import minidom
name = [{'vehicle': 'honda'}, {'vehicle': 'hyundai'}, {'vehicle': 'mercedes'}, {'vehicle': 'rangerover'}, {'vehicle': 'bentley'}, {'vehicle': 'toyota'}, {'vehicle': 'mecerati'}, {'vehicle': 'lamborgini'}]
l = [(0, 1), (0, 2), (0, 3), (0, 4), (0, 5), (0, 6), (0, 7), (1, 0), (1, 2)]
for step in range(10): 
            i,j = l[step]                      
            print(i,j)
            name1 = str(name[i]['vehicle'])
            root = Element('annotation')
            folder = SubElement(root, 'folder')
            folder.text="testing"
            filename=SubElement(root, 'filename')
            filename.text="1.jpg"
            path=SubElement(root, 'path')
            path.text="path"
            source=SubElement(root, 'source')           
            obj=SubElement(root, 'object')
            name=SubElement(obj,'name')
            name.text=str(name1)                                    
            tree = ET.ElementTree(root)
            tree.write(os.path.join('testing',str(step)+".xml"))  

当使用相同的i值进行第二次迭代时,将引发错误。

    0 1
    0 2
---> 10             name1 = str(name[i]['vehicle'])


IndexError: child index out of range

您能帮我弄清楚我在做什么错以及解决方法吗?我发现了一个类似的问题,但是并没有解决我的错误Child索引超出范围,python元素树

尼克·克莱恩(Niek de Klein)

在您的for循环中name=SubElement(obj,'name'),您将覆盖原始名称列表。将该变量名称更改为其他名称。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

base64编码字节数组时,为什么会出现“索引超出范围”错误?

尝试写入文件时索引超出范围

为什么我的列表中出现字符串超出范围索引错误?

为什么会出现运行时错误:向量擦除迭代器超出范围

通过Postgresql中的函数删除记录时,为什么会出现“超出bigint范围”错误?

为什么错误显示“ ArgumentException:索引超出范围”。当我在Unity中获得触摸增量位置时?

在进行漂亮的汤解析的for循环期间,为什么会出现“ IndexError:列表索引超出范围”?

使用串联的数据框时,为什么会出现“ IndexError:字符串索引超出范围”

IndexError:写入文件时列出索引超出范围

在Python的while循环中追加列表会出现错误消息“列表索引超出范围”

为什么会出现错误:列表索引超出范围

为什么在打印列表时没有错误时出现IndexError:字符串索引超出范围?

为什么为什么不断出现错误“ IndexError:列表索引超出范围”?

在rust中写入文件时,为什么会出现“错误文件描述符”错误?

将Byte数组复制到Struct数组时,为什么会出现“索引超出范围”异常?

为什么在创建类的实例时出现“列表索引超出范围”错误?

为什么运行此程序时出现“字符串索引超出范围”错误?

字符串索引超出范围:2不知道为什么会出现这种情况

为什么会出现“下标超出范围”错误?

为什么索引超出范围?(Python)

当我的代码尝试用我的刽子手游戏中的字母替换丢失的字母时,为什么会出现“字符串索引超出范围”

为什么函数在 Python 中返回错误“列表索引超出范围”?

Python读取XML文件不断出现错误“列表索引超出范围”

tableview 单元格中的 uicollection 视图出现错误:索引超出范围,为什么?

为什么会出现“IndexError:字符串索引超出范围”?

为什么“列表索引超出范围”错误仅在我输入 10 时出现?

抓取错误:索引错误:在python中列出索引超出范围(在csv上写入)

Python 列表列表为什么会出现此错误:IndexError:列表索引超出范围?

当我所做的只是遍历列表的长度时,为什么会出现索引超出范围错误?