簡體   English   中英

如何在使用python xml.etree.ElementTree生成xml文件時修復unicode錯誤而又不丟失任何數據?

[英]How to fix unicode error while generating xml file using python xml.etree.ElementTree without misssing any data?

我正在使用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)

以下是腳本:

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="  ")

##Here starts populating elements inside xml file
top = Element('my_practice_document')
comment = Comment('details')
top.append(comment)
child = SubElement(top, 'my_information')
childs = SubElement(child,'my_name')
childs.text = str(options.my_name)

#Following section is for retrieving list of software installed on the system
import wmi
w = wmi.WMI()
for p in w.Win32_Product():
if (p.Version is not None) and (p.Caption is not None):
    child = SubElement(top, 'sys_info') 
    child.text =  p.Caption + " version "+ p.Version 

## Following portion places the xml output into test.xml file
with open("test.xml", 'w') as f:
    f.write(prettify(top))

執行腳本后,出現unicode錯誤。 我在互聯網上搜索並嘗試了以下方法:

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

但這也沒有解決我的問題。 我希望將控制台上獲取的所有數據都放入文件中,而不會丟失任何內容。 所以,我怎么能做到這一點。 提前感謝您的協助。

您需要為輸出文件指定編碼。 sys.setdefaultencoding不會為您執行此操作。

嘗試

import codecs
with codecs.open("test.xml", 'w', encoding='utf-8') as f:
    f.write(prettify(top))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM