I'm trying to write an XML file using Python's ElementTree package. Basically I make a root element called allDepts, and then in each iteration of my for loop I call a function that returns a deptElement containing a bunch of information about a university department. I add every deptElement to allDepts, make an ElementTree out of allDepts, and try to write it to a file.
def crawl(year, season, campus):
departments = getAllDepartments(year, season, campus)
allDepts = ET.Element('depts')
for dept in departments:
deptElement = getDeptElement(allDepts, dept, year, season, campus)
print ET.tostring(deptElement) #Prints fine here!
ET.SubElement(allDepts, deptElement)
if deptElement == None:
print "ERROR: " + dept
with open(str(year) + season + "_" + campus + "_courses.xml", 'w') as f:
tree = ET.ElementTree(allDepts)
tree.write(f)
For some reason, at the tree.write(f) line, I get this error: "TypeError: cannot concatenate 'str' and 'instance' objects". Each deptElement prints out fine in the for loop, making me think that getDeptElement() is working fine. I never get my "ERROR" message printed out. Does anyone know what I'm doing wrong?
EDIT: Here's the full stack trace:
File "./CourseInfoCrawl.py", line 210, in <module>
crawl("2013", "S", "UBC")
File "./CourseInfoCrawl.py", line 207, in crawl
tree.write(f)
File "/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/xml/etree/ElementTree.py", line 663, in write
self._write(file, self._root, encoding, {})
File "/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/xml/etree/ElementTree.py", line 707, in _write
self._write(file, n, encoding, namespaces)
File "/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/xml/etree/ElementTree.py", line 681, in _write
file.write("<" + _encode(tag, encoding))