22-12-2011

Python CSV to XML script

This is an example script processing data from two different CSV files and writing the combined data to an XML file.

from xml.dom.minidom import Document
 
list = []
dat = []
ldap = []
doc = Document(); 
 
def createnode(name,contents,parentnode):
	node = doc.createElement(name)
	textnode = doc.createTextNode(contents)
	node.appendChild(textnode)
	parentnode.appendChild(node)
 
# read in the data from the first file
f = open("netids.txt")
for line in f:
	list.append(line.strip().lower())
f.close()
 
#pick the relevant info from second file
f = open("data.csv")
for line in f:
	dat = line.split(';')
	if	list.count(dat[0].lower()):
		ldap.append(dat)
f.close()
 
# Create the base XML element
contacts = doc.createElement("contacts")
doc.appendChild(contacts)
 
# create nodes
for csvlist in ldap:
	contact = doc.createElement("contact")
	contact.setAttribute("net", csvlist[0].lower())
 
# use function to avoid repetition	
 
	createnode("email",csvlist[-2],contact)
	createnode("naam",csvlist[1],contact)
	createnode("tel",csvlist[-4],contact)
 
	contacts.appendChild(contact)
 
#print doc.toprettyxml(indent="  ") 
 
f = open('auto.xml', 'w')
doc.writexml(f,indent="  ",addindent="	",newl="\n")
f.close()

Comments:

Your comment:

»

 

[x]