1

I'm using the following script to convert my XML products to 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)

When I run the script:

python convert.py ItemCatDesc2.xml > ItemCatDesc2.csv

I get the following error:

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)

The XML I'm converting is

<?xml version="1.0" encoding="UTF-8" ?>
Alastair McCormack
  • 26,573
  • 8
  • 77
  • 100
Pop
  • 57
  • 1
  • 8

1 Answers1

-1

Try this:

# -*- coding: utf-8 -*-
Fuk Yu
  • 173
  • 1
  • 9
  • Yeah, I had already tried that, same result. UnicodeEncodeError: 'ascii' codec can't encode character u'\xbd' in position 362: ordinal not in range(128) – Pop Aug 15 '16 at 18:37
  • `# -*- coding:` is only used when the **source code** contains non-ascii, which is not the case here – Alastair McCormack Aug 15 '16 at 19:58