如何解决Python 3:print() 在合并两个 xml 时不处理“\n”
merge.py:
import sys
from xml.etree import ElementTree
def run(files):
first = None
for filename in files:
data = ElementTree.parse(filename).getroot()
if first is None:
first = data
else:
first.extend(data)
if first is not None:
print (ElementTree.tostring(first))
if __name__ == "__main__":
files = None
if len(sys.argv[1:]) != 0:
files = "".join(sys.argv[1:]).split('\n')
run(files)
else:
raise Exception("Sorry,no files found")
运行上述将 xmls 文件合并为一个的代码时,输出如下所示,提供的输出最少:
预期输出:
<a>
<b> ---ABCD
-----</b>
实际输出:
<a><b> ---ABCD\n----</b>
如何称呼:
python3 merge.py `find "path/" -type f -name *.xml"` > "path/combined.xml"
PS:它适用于 Python。仅在 Python3 中观察到。
解决方法
如 here 所述,ElementTree.tostring()
的默认编码为 US-ASCII
。将 encoding
参数设置为 unicode
。这将相应地解析 \n
。
ElementTree.tostring(first,encoding="unicode"))
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。