用python批量生成简单的xml文档

  最近生成训练数据时,给一批无效的背景图片生成对应的xml文档,我用python写了一个简单的批量生成xml文档的demo,遇见了意外的小问题,记录一下。

  报错问题为:ImportError: No module named 'xml.dom'; 'xml' is not a package

  看见No module named “xxx”时想的是不就是没安装xml包嘛,还不简单,install一下不就好了,然而并没什么用,xml是python本生就带的。其实出现这种错误的原因是自己的命名规则问题,将python程序命名为"xml.py"导致的。让运行python程序时出现自导现象,从而出错。一个小错误,发现时我自己都笑了。

  顺便贴一下代码,作为一个小demo分享一下。

  

import os
import xml.dom.minidom

read_file='jpg'

for file_name in os.listdir(read_file):
    new_txtname=file_name.split('.')[0]


    #创建一个空的Dom文档对象
    doc = xml.dom.minidom.Document()
    #创建根节点,此根节点为annotation
    annotation = doc.createElement('annotation')
    #将根节点添加到DOm文档对象中
    doc.appendChild(annotation) 

    folder = doc.createElement('folder')
    #内容写入
    folder_text = doc.createTextNode('ee')
    folder.appendChild(folder_text)
    annotation.appendChild(folder)

    filename = doc.createElement('filename')
    filename_text = doc.createTextNode(file_name)
    filename.appendChild(filename_text)
    annotation.appendChild(filename)

    path = doc.createElement('path')
    path_text = doc.createTextNode('path is null')
    path.appendChild(path_text)
    annotation.appendChild(path)

    source = doc.createElement('source')
    databass = doc.createElement('databass')
    databass_text = doc.createTextNode('Unknown')
    source.appendChild(databass)
    databass.appendChild(databass_text)
    annotation.appendChild(source)

    size = doc.createElement('size')
    width = doc.createElement('width')
    width_text = doc.createTextNode('875')
    height = doc.createElement('height')

    height_text = doc.createTextNode('656')
    depth = doc.createElement('depth')
    depth_text = doc.createTextNode('1')
    size.appendChild(width)
    width.appendChild(width_text)
    size.appendChild(height)
    height.appendChild(height_text)
    size.appendChild(depth)
    depth.appendChild(depth_text)
    annotation.appendChild(size)

    segmented = doc.createElement('segmented')
    segmented_text = doc.createTextNode('0')
    segmented.appendChild(segmented_text)
    annotation.appendChild(segmented)

    #写入xml文本文件中
    fp = open('xml/%s.xml' %new_txtname , 'w+')
    doc.writexml(fp, indent='\t', addindent='\t', newl='\n',encoding='utf-8')
    fp.close()

  

posted @ 2018-08-13 16:44  lvsling  阅读(3619)  评论(0编辑  收藏  举报