解析.xml文件中的数据时出现KeyError

问题描述 投票:0回答:1

我是初学者,正在尝试从.xml文件中解析某些数据,该文件的结构如下。

<parking id="pucpr">
  <space id="1" occupied="0">
    <rotatedRect>
      <center x="300" y="207" />
      <size w="55" h="32" />
      <angle d="-74" />
    </rotatedRect>
    <contour>
      <point x="278" y="230" />
      <point x="290" y="186" />
      <point x="324" y="185" />
      <point x="308" y="230" />
    </contour>
  </space>
  <space id="2" occupied="0">
    <rotatedRect>
      <center x="332" y="209" />
      <size w="56" h="33" />
      <angle d="-77" />
    </rotatedRect>
    <contour>
      <point x="325" y="185" />
      <point x="355" y="185" />
      <point x="344" y="233" />
      <point x="310" y="233" />
    </contour>
  </space>
.
.
.
</parking>

在不同的文件夹中有数百个这样的文件。我写了下面的代码来解析所有这些.xml文件中的数据。

import xml.etree.ElementTree as ET
import os
import xlsxwriter

data_path = '/Users/jaehyunlee/Desktop/for_test'

# Read full directory and file name in the folder
for path, dirs, files in os.walk(data_path):
    for file in files:
        if os.path.splitext(file)[1].lower() == '.xml': # filtering only for .xml files
            full_path = os.path.join(path, file)

            # Parsing data from .xml file
            tree = ET.parse(full_path)
            root = tree.getroot()

            for space in root.iter('space'):
                car = space.attrib["occupied"]
                car_int = int(car)

当我尝试解析“已占用”属性的值时,会发生问题。当我运行代码时,它返回KeyError:'occupied'。对于其他属性,例如“ x”,“ y”,“ w”,“ h”,它可以很好地工作。有人可以帮忙吗?

ps.s。当我分别转换一个.xml文件时,不会发生此错误。但是,当我尝试遍历文件夹中的所有文件时,就会发生这种情况。

python xml parsing attributes keyerror
1个回答
0
投票
‰PNG
© www.soinside.com 2019 - 2024. All rights reserved.