1
我用下面的脚本到我的XML产品转换为CSVUnicodeEncodeError时CSV文件
#!/usr/bin/python
from xml.etree import ElementTree as ET
import csv
tree = ET.parse('ItemCatDesc2.xml')
root = tree.getroot()
columns = ['Name'] + [value.attrib.get('AttributeID') for value in tree.findall('.//Product//Value')]
with open('ItemCatDesc2.csv', 'w') as ofile:
ofile = csv.DictWriter(ofile, set(columns))
ofile.writeheader()
for product in tree.findall('.//Product'):
d = {value.attrib.get('AttributeID') : value.text
for value in product.findall('.//Values/Value')}
d['Name'] = product.findtext('Name')
print d
ofile.writerow(d)
当我运行该脚本:
python convert.py ItemCatDesc2.xml > ItemCatDesc2.csv
我得到以下错误:
Traceback (most recent call last):
File "convert.py", line 21, in <module>
ofile.writerow(d)
File "/usr/lib/python2.7/csv.py", line 152, in writerow
return self.writer.writerow(self._dict_to_list(rowdict))
UnicodeEncodeError: 'ascii' codec can't encode character u'\xbd' in position 362: ordinal not in range(128)
我正在转换的XML是
<?xml version="1.0" encoding="UTF-8" ?>
是的,我已经试过了,同样的结果。 UnicodeEncodeError:'ascii'编解码器无法编码字符u'\ xbd'在位置362:序号不在范围内(128) – Pop
'# - * - coding:'仅在**源代码**包含非-ascii,这不是这里的情况 –