Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/340.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在使用python xml.etree.ElementTree生成xml文件时修复unicode错误,而不丢失任何数据?_Python_Xml_Unicode String - Fatal编程技术网

如何在使用python xml.etree.ElementTree生成xml文件时修复unicode错误,而不丢失任何数据?

如何在使用python xml.etree.ElementTree生成xml文件时修复unicode错误,而不丢失任何数据?,python,xml,unicode-string,Python,Xml,Unicode String,我使用python中的xml.etree.ElementTree生成xml文件,然后将生成的xml文件写入文件。xml的一个标签是关于系统安装的软件,其中包含系统安装软件的所有详细信息。我在执行脚本时在控制台上获得的xml输出是完美的,但当我尝试将输出放入文件时,我遇到以下错误: Traceback (most recent call last): File "C:\xmltry.py", line 65, in <module> f.write(prettify(top)) Uni

我使用python中的xml.etree.ElementTree生成xml文件,然后将生成的xml文件写入文件。xml的一个标签是关于系统安装的软件,其中包含系统安装软件的所有详细信息。我在执行脚本时在控制台上获得的xml输出是完美的,但当我尝试将输出放入文件时,我遇到以下错误:

Traceback (most recent call last):
File "C:\xmltry.py", line 65, in <module>
f.write(prettify(top))
UnicodeEncodeError: 'ascii' codec can't encode character u'\xf1' in position 4305: ordinal not in range(128)
当脚本执行时,我得到unicode错误。我在互联网上搜索并尝试了以下内容:

import sys
reload(sys)
sys.setdefaultencoding('utf8')

但这也没有解决我的问题。我希望将控制台上获取的所有数据都保存到文件中,而不丢失任何内容。那么,我怎样才能做到这一点呢。谢谢您的帮助。

您需要为输出文件指定编码
sys.setdefaultencoding
不会为您这样做

试一试


我按照你说的做了,现在我得到了以下错误:回溯(最近一次调用最后一次):文件“C:\xmltry.py”,第62行,在打印p.Caption+“version”+p.version文件“C:\programs\Python27\lib\encodings\cp437.py”,第12行,在encode返回codecs.charmap\u encode(输入,错误,编码\u-map)UnicodeEncodeError:“charmap”编解码器无法对位置0-4中的字符进行编码:字符映射到。我该怎么解决呢?我从命令行执行了脚本。这是另一个问题-您似乎正在向控制台打印Unicode字符串,而控制台使用的DOS代码页无法显示这些字符。在打印字符串之前,请尝试对字符串进行
.encode(“cp437”,errors=“replace”)
import sys
reload(sys)
sys.setdefaultencoding('utf8')
import codecs
with codecs.open("test.xml", 'w', encoding='utf-8') as f:
    f.write(prettify(top))