如何直接将代码应用于所有文件并将xml文件转换为txt文件

问题描述

我正在尝试在python中应用代码以从每个xml文件提取必要的信息,并将其写入txt文件中。 我成功执行了代码,但结果仅显示一个文件。 另外,我的代码看起来并不聪明,如果有人可以帮助我解决问题并给予纠正,我将非常高兴。

恐怕我是个初学者,所以我可能会有很多基本的错误...

这是我的代码


from xml.etree import ElementTree as ET
import os

path = r'/Users/mo/Documents/annotations/xmls'
filenames = []

for filename in os.listdir(path):
    if not filename.endswith('.xml'):
        continue
    fullname = os.path.join(path,filename)
    filenames.append(fullname)

each_name = filename[:-4]

with open(each_name + '.txt','a') as f:

    for filename in filenames:
        tree = ET.parse(filename)
        root = tree.getroot()

        for object in root.findall('object'):
            categoryID = object.find('name').text

            for bnd_Box in object.findall('bndBox'):
                Xcenter = (int(bnd_Box.find('xmax').text) - int(bnd_Box.find('xmin').text))/2
                Ycenter = (int(bnd_Box.find('ymax').text) - int(bnd_Box.find('ymin').text))/2
                width = int(bnd_Box.find('xmax').text)- int(bnd_Box.find('xmin').text)
                height = int(bnd_Box.find('ymax').text) - int(bnd_Box.find('ymin').text)
                Detection_rows = str(categoryID) + str(Xcenter) + str(Ycenter) + str(width) + str(height) + '\n'

    f.write(str(Detection_rows))

非常感谢您

解决方法

尝试一下(未测试

from xml.etree import ElementTree as ET
import os

path = r'/Users/mo/Documents/annotations/xmls'

for filename in os.listdir(path):
    if not filename.endswith('.xml'):
        continue
        
    fullname = os.path.join(path,filename)

    with open(fullname[:-4] + '.txt','a') as f:

        tree = ET.parse(fullname)
        root = tree.getroot()

        for object in root.findall('object'):
            categoryID = object.find('name').text

            for bnd_box in object.findall('bndbox'):
                Xcenter = (int(bnd_box.find('xmax').text) - int(bnd_box.find('xmin').text))/2
                Ycenter = (int(bnd_box.find('ymax').text) - int(bnd_box.find('ymin').text))/2
                width = int(bnd_box.find('xmax').text)- int(bnd_box.find('xmin').text)
                height = int(bnd_box.find('ymax').text) - int(bnd_box.find('ymin').text)
                Detection_rows = str(categoryID) + str(Xcenter) + str(Ycenter) + str(width) + str(height) + '\n'

        f.write(str(Detection_rows))

您的for循环应位于open之外,并且您将filenames更改为filename。另外,我删除了一个不必要的for循环。让我知道它是否可以为您解决问题。