写入文件时,Python正在删除xml声明中的编码

时间:2019-07-04 13:42:19

标签: python-3.x utf-8 io elementtree pretty-print

我有此代码:

    from xml.etree import ElementTree as et
    from xml.dom import minidom
    from io import BytesIO
    [...]
    tree = et.ElementTree(root)
    f = BytesIO()
    tree.write(f, encoding='utf-8', xml_declaration=True)
    print(f.getvalue())
    xmlstr = minidom.parseString(f.getvalue()).toprettyxml(indent="   ")
    with open("output/Task_Score_Value." + str(sheet.cell(row=line, column=1).value) + ".md", "w+") as file:
        print(xmlstr)
        file.write(xmlstr)

我得到以下输出(我只打印第一行)

b'<?xml version=\'1.0\' encoding=\'utf-8\'?>\n<CustomMetadata xmlns="http://soap.[...]
<?xml version="1.0" ?>
<CustomMetadata xmlns="http://soap.[...]
[...]

为什么要在第二张照片中(当然,也在文件中)删除“ encoding = UTF-8”?

0 个答案:

没有答案