如何使用pythonxml.etree在一个新行文件中获取xml输出?

如何使用pythonxml.etree在一个新行文件中获取xml输出?,python,xml,python-2.7,file-io,elementtree,Python,Xml,Python 2.7,File Io,Elementtree,我使用“from xml.etree import ElementTree”生成xml文件,并将生成的输出放入新文件“test.xml”中。输出放在test.xml中,但是没有新行,这是一条大行。那么,我该如何在“test.xml”中添加新行呢。以下是脚本: from xml.etree import ElementTree from xml.dom import minidom from lxml import etree def prettify(elem): """Return a

我使用“from xml.etree import ElementTree”生成xml文件,并将生成的输出放入新文件“test.xml”中。输出放在test.xml中,但是没有新行,这是一条大行。那么,我该如何在“test.xml”中添加新行呢。以下是脚本:

from xml.etree import ElementTree
from xml.dom import minidom
from lxml import etree
def prettify(elem):
    """Return a pretty-printed XML string for the Element.
    """
    rough_string = ElementTree.tostring(elem, 'utf-8')
    reparsed = minidom.parseString(rough_string)
    return reparsed.toprettyxml(indent="  ")
top = Element('my_document')
comment = Comment('Practising')
top.append(comment)
child = SubElement(top, 'my_information')
childs = SubElement(child,'my_name')
childs.text = 'This child contains text.'
print prettify(top)
file = open("test.xml", 'w')
xml.ElementTree(top).write(file)
file.close()

为什么不使用
修饰的返回值?编写函数的返回值将解决您的问题

...
top = Element('my_document')
comment = Comment('Practising')
top.append(comment)
child = SubElement(top, 'my_information')
childs = SubElement(child,'my_name')
childs.text = 'This child contains text.'
with open("test.xml", 'w') as f:  # <--
    f.write(prettify(top))        # <--
。。。
top=元素(“我的文档”)
注释=注释('练习')
top.append(注释)
child=子元素(顶部“我的信息”)
childs=子元素(child,'my_name')
childs.text='此子级包含文本。'

用open(“test.xml”,“w”)作为f:#为什么不使用
prettify
的返回值?编写函数的返回值将解决您的问题

...
top = Element('my_document')
comment = Comment('Practising')
top.append(comment)
child = SubElement(top, 'my_information')
childs = SubElement(child,'my_name')
childs.text = 'This child contains text.'
with open("test.xml", 'w') as f:  # <--
    f.write(prettify(top))        # <--
。。。
top=元素(“我的文档”)
注释=注释('练习')
top.append(注释)
child=子元素(顶部“我的信息”)
childs=子元素(child,'my_name')
childs.text='此子级包含文本。'
将open(“test.xml”,“w”)作为f:#