我正在尝试使用 Python 的 ElementTree 包编写 XML 文件。基本上,我创建了一个名为 的根元素allDepts
,然后在我的 for 循环的每次迭代中,我调用一个函数,该函数返回一个deptElement
包含有关大学部门的一堆信息的函数。我将每个添加deptElement
到allDepts
,制作ElementTree
出allDepts
,并尝试将其写入文件。
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)
出于某种原因,在该tree.write(f)
行中,我收到此错误:“TypeError:无法连接 'str' 和 'instance' 对象”。每个都deptElement
在 for 循环中打印得很好,让我觉得这getDeptElement()
很好。我从来没有打印出我的“错误”消息。有谁知道我做错了什么?
编辑:这是完整的堆栈跟踪:
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))