首页 > 解决方案 > 在使用 xml ElementTree 时,我随机得到 IOError

问题描述

在使用 时xml.etree.ElementTree,我随机进入IOError: [Errno 0] Error脚本执行的中间。

我确实有非常简单的脚本:

import xml.etree.ElementTree as ET

root = ET.parse('movie.xml').getroot()
for movie in root.iter('movie'):
    print(movie.attrib)

和xml:

 <collection>
        <genre category="Action">
            <decade years="1980s">
                <movie favorite="True" title="Indiana Jones: The raiders of the lost Ark">
                    <format multiple="No">DVD</format>
                    <year>1981</year>
                    <rating>PG</rating>
                    <description>
                    'Archaeologist and adventurer Indiana Jones 
                    is hired by the U.S. government to find the Ark of the 
                    Covenant before the Nazis.'
                    </description>
                </movie>
                   <movie favorite="True" title="THE KARATE KID">
                   <format multiple="Yes">DVD,Online</format>
                   <year>1984</year>
                   <rating>PG</rating>
                   <description>None provided.</description>
                </movie>
                <movie favorite="False" title="Back 2 the Future">
                   <format multiple="False">Blu-ray</format>
                   <year>1985</year>
                   <rating>PG</rating>
                   <description>Marty McFly</description>
                </movie>
            </decade>
            <decade years="1990s">
                <movie favorite="False" title="X-Men">
                   <format multiple="Yes">dvd, digital</format>
                   <year>2000</year>
                   <rating>PG-13</rating>
                   <description>Two mutants come to a private academy for their kind whose resident superhero team must 
                   oppose a terrorist organization with similar powers.</description>
                </movie>
                <movie favorite="True" title="Batman Returns">
                   <format multiple="No">VHS</format>
                   <year>1992</year>
                   <rating>PG13</rating>
                   <description>NA.</description>
                </movie>
                   <movie favorite="False" title="Reservoir Dogs">
                   <format multiple="No">Online</format>
                   <year>1992</year>
                   <rating>R</rating>
                   <description>WhAtEvER I Want!!!?!</description>
                </movie>
            </decade>    
        </genre>
</collection>

有时脚本会立即抛出异常,有时它会循环一些元素然后抛出,有时它会通过。

示例输出如下所示:

{'favorite': 'True', 'title': 'Indiana Jones: The raiders of the lost Ark'}
{'favorite': 'True', 'title': 'THE KARATE KID'}
{'favorite': 'False', 'title': 'Back 2 the Future'}
{'favorite': 'False', 'title': 'X-Men'}
{'favorite'Traceback (most recent call last):
  File "test.py", line 6, in <module>
    print(movie.attrib)
IOError: [Errno 0] Error

知道我做错了什么吗?

标签: pythonpython-2.7

解决方案


推荐阅读