【发布时间】:2014-06-07 22:22:57
【问题描述】:
我目前正在编写一个简短的 Python 脚本来遍历服务器上的一些目录,找到我要查找的内容并将数据保存到 XML 文件中。
问题是某些数据是用其他语言编写的,例如“ハローワールド”或类似格式的东西。当尝试将其保存在我的 XML 中的条目中时,我得到以下回溯:
UnicodeDecodeError: 'ascii' codec can't decode byte 0xec in position 18: ordinal not in range(128)
这是我保存数据的函数的样子:
def addHistoryEntry(self, title, url):
self.log.info('adding history entry {"title":"%s", "url":"%s"}' % (title, url))
root = self.getRoot()
history = root.find('.//history')
entry = etree.SubElement(history, 'entry')
entry.set('title', title)
entry.set('time', str(unixtime()))
entry.text = url
history.set('results', str(int(history.attrib['results']) + 1))
self.write(root)
self.getRoot() 如下:
def getRoot(self):
return etree.ElementTree(file = self.config).getroot()
这里是写入数据的函数 (self.write(root))
def write(self, xmlRoot):
bump = open(self.config, 'w+')
bump.write(dom.parseString(etree.tostring(xmlRoot, 'utf-8')).toxml())
bump.close()
进口是:
import xml.etree.ElementTree as etree
import xml.dom.minidom as dom
如果有人能帮我解决这个问题,请做。 感谢您的帮助。
【问题讨论】:
-
使用
decode('utf-8') -
使用
codecs.open()-- stackoverflow.com/questions/934160/…