解析.xml文件中的数据时发生KeyError

2024-04-26 13:56:37 发布

您现在位置:Python中文网/ 问答频道 /正文

我是一名初学者,正在尝试解析.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)

当我试图解析属性“acculated”的值时,问题就出现了。当我运行代码时,它返回KeyError:“已占用”。 对于其他属性,例如“x”、“y”、“w”、“h”,它工作得非常好。 有人能帮忙吗

另外,当我单独转换一个.xml文件时,不会发生此错误。但当我尝试迭代文件夹中的所有文件时,就会发生这种情况


Tags: 文件pathinimportidfordataos
1条回答
网友
1楼 · 发布于 2024-04-26 13:56:37

我发现发生此键错误是因为某些文件不包含“已占用”属性。为了避免这个问题并继续迭代,我在“for”下面添加了“if”

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:
                if 'occupied' in space.attrib:
                    car = space.attrib['occupied'] 
                    car_int = int(car)

相关问题 更多 >