[英]XML write to file UnicodeDecodeError Python 2.7.3
我搜索了網站,但沒有找到適合我的答案。 我的問題是我正在嘗試將xml寫入文件,當我從終端運行腳本時,我得到:
Traceback (most recent call last):
File "fetchWiki.py", line 145, in <module>
pageDictionary = qSQL(users_database)
File "fetchWiki.py", line 107, in qSQL
writeXML(listNS)
File "fetchWiki.py", line 139, in writeXML
f1.write(doc.toprettyxml(indent="\t", encoding="utf-8"))
File "/usr/lib/python2.7/xml/dom/minidom.py", line 57, in toprettyxml
self.writexml(writer, "", indent, newl, encoding)
File "/usr/lib/python2.7/xml/dom/minidom.py", line 1751, in writexml
node.writexml(writer, indent, addindent, newl)
----//---- more lines in here ----//----
self.childNodes[0].writexml(writer, '', '', '')
File "/usr/lib/python2.7/xml/dom/minidom.py", line 1040, in writexml
_write_data(writer, "%s%s%s" % (indent, self.data, newl))
File "/usr/lib/python2.7/xml/dom/minidom.py", line 297, in _write_data
writer.write(data)
File "/usr/lib/python2.7/codecs.py", line 351, in write
data, consumed = self.encode(object, self.errors)
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc2 in position 1176: ordinal not
in range(128)
這是從下面的代碼:
doc = Document()
base = doc.createElement('Wiki')
doc.appendChild(base)
for ns_dict in listNamespaces:
namespace = doc.createElement('Namespace')
base.appendChild(namespace)
namespace.setAttribute('NS', ns_dict)
for title in listNamespaces[ns_dict]:
page = doc.createElement('Page')
try:
title.encode('utf8')
page.setAttribute('Title', title)
except:
newTitle = title.decode('latin1', 'ignore')
newTitle.encode('utf8', 'ignore')
page.setAttribute('Title', newTitle)
namespace.appendChild(page)
text = doc.createElement('Content')
text_content = doc.createTextNode(listNamespaces[ns_dict][title])
text.appendChild(text_content)
page.appendChild(text)
f1 = open('pageText.xml', 'w')
f1.write(doc.toprettyxml(indent="\t", encoding="utf-8"))
f1.close()
使用或不使用“編碼/解碼” igonore”參數,都會發生錯誤。 添加
# -*- coding: utf-8 -*-
沒有幫助。
我使用Eclipse和Pydoc創建了python文檔,它沒有任何問題,但是當我從終端運行時它出錯了。
非常感謝任何幫助,包括我沒有找到的答案的鏈接。
謝謝。
您不應編碼用於屬性的字符串。 minidom
庫在編寫時會為您處理。
您的錯誤是由字節串與unicode數據混合引起的,並且您的編碼字節串不能以ASCII格式解碼。
如果您的某些數據是編碼的,並且其中一些數據是unicode
,請首先嘗試避免這種情況。 如果您無法避免必須處理混合數據,請執行以下操作:
page = doc.createElement('Page')
if not isinstance(title, unicode):
title = title.decode('latin1', 'ignore')
page.setAttribute('Title', title)
請注意,您不需要使用doc.toprettyxml()
; 您可以指示doc.writexml()
為您縮進XML:
import codecs
with codecs.open('pageText.xml', 'w', encoding='utf8') as f1:
doc.writexml(f1, indent='\t', newl='\n')
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.