最近生成訓練數據時,給一批無效的背景圖片生成對應的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()