我的程序基本上读取一个输入文件,从该文件中生成一个lxml.etree,比如我向etree添加一个节点,然后我想将它打印回文件。 所以将它写回我用一个文件:使用lxml格式化输出为XML
et.write('Documents\Write.xml', pretty_print=True)
和输出我是:
<Variable Name="one" RefID="two"><Component Type="three"><Value>four</Value></Component></Variable>
虽然我想是这样的:
<Variable Name="one" RefID="two">
<Component Type="three">
<Value>four</Value>
</Component>
</Variable>
上午在哪里我弄错了?我已经尝试了很多解决方案,但似乎没有任何工作(美丽,整洁,解析器...)
它可以与Windows相关吗?如果你尝试使用'io'模块打开你的输出文件:'fp = io.open('Documents \ Write.xml','w',newline ='\ r \ n') 然后'写入'fp ''就像'et.write(fp,pretty_print = True)' (见http://docs.python.org/2/library/io.html#io.open) –
嗨,保罗,我正在尝试你说,但是什么是fp?我想写的文件?对不起,我是初学者! – JAWE
只是表示要写入的文件的文件指针,是的。 'et.write()'可以将一个文件名或一个打开的文件指针作为输入,就像来自'io.open'的东西(http://lxml.de/api/lxml.etree._ElementTree-class.html#write )。你可以尝试'导入io',然后'et.write(io.open('Documents \ Write.xml','w',newline ='\ r \ n'),pretty_print = True)' –