2016-08-15 76 views
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" ?> 

回答

-1

試試這個:

# -*- coding: utf-8 -*- 
+0

是的,我已經試過了,同樣的結果。 UnicodeEncodeError:'ascii'編解碼器無法編碼字符u'\ xbd'在位置362:序號不在範圍內(128) – Pop

+0

'# - * - coding:'僅在**源代碼**包含非-ascii,這不是這裏的情況 –