python导出xml文件_用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()

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值