附加文件而不是覆盖文件(“ ab”不起作用)

时间:2018-08-31 06:58:08

标签: python xml

我正在尝试使用下面的代码将列表元素写入xml文件。问题在于代码仅将列表(i)的最后一个元素写入xml文件,而不是附加xml文件以包括i的所有迭代。

代码:

. 
. 
. 
image_name = attributes[0]
xmin = (attributes[2:totalAttributes:5])
ymin = (attributes[3:totalAttributes:5])
xmax = (attributes[4:totalAttributes:5])
ymax = (attributes[5:totalAttributes:5])
item_name = (attributes[6:totalAttributes:5])
segmented = str(0)
print (image_name, xmin, xmax, ymin, ymax, item_name)

basename = image_name.split(".", 1)[0]
# print (basename)
i = 0

while len(xmin) > i:

    # ## Setting xml file variables here
    root = etree.Element("annotation")
    etree.SubElement(root, "folder").text = "images"
    etree.SubElement(root, "filename").text = image_name

    size = etree.SubElement(root, "size")
    #size.text = "Child 3"
    etree.SubElement(size, "width").text = "448"
    etree.SubElement(size, "height").text = "448"

    etree.SubElement(root, "segmented").text = segmented

    obj = etree.SubElement(root, "object")
    etree.SubElement(obj, "name").text = item_name[i]
    bndbox = etree.SubElement(obj, "bndbox")
    etree.SubElement(bndbox, "xmin").text = xmin[i]
    etree.SubElement(bndbox, "ymin").text = ymin[i]
    etree.SubElement(bndbox, "xmax").text = xmax[i]
    etree.SubElement(bndbox, "ymax").text = ymax[i]

    with open('/Users/vivek/Desktop/test/' + basename +  '.xml', "wb") as outputFile:
        outputFile.write(etree.tostring(root, pretty_print = True))

    i = i + 1

我知道,为了追加到文件外,我们在with open('/Users/Desktop/test/' + basename + '.xml', "wb") as outputFile:行中使用'a'而不是'wb',但是当我尝试这样做时,出现以下错误:

Traceback (most recent call last):
  File "darkflow_to_xml_rev2.py", line 53, in <module>
    outputFile.write(etree.tostring(root, pretty_print = True))
TypeError: write() argument must be str, not bytes

此外,在将“ a”更改为“ ab”时,我得到一个空的xml文件作为输出。获得有关我在此处缺少的内容的指导会很棒。

0 个答案:

没有答案