I am a novice using Python2.7 and am having problems writing data to a csv file while the data sometimes has 'special' characters like for example è.
I tried to solve this (following advice provided on this forum before) by a number of things (basically trial and error method for me):
- adding encoding='utf-8' as argument in the open(filename) method
- adding 'import unicodecsv as csv' to my script
- importing io and changing open(filename) into io.open(filename)
- added special comment lines at the top following instructions from http://python.org/dev/peps/pep-0263/
Here is the part of the code that is supposed to do the job:
#!/usr/bin/python
# -*- coding: latin-1 -*-
import unicodecsv as csv
import io
outputfile = io.open('/Data/test.txt', 'w+', encoding='utf-8')
header1 = (u'cc number',u'company name')
table1 = [header1]
tuple1 = (u'34452801', u'Bèlvédère')
table1.append(tuple1)
cc_entry_writer = csv.writer(outputfile, delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL)
for row in table1:
cc_entry_writer.writerow(row)
However this results in the following error:
TypeError: write() argument 1 must be unicode, not str
So, apparently I still have got something wrong. I checked myself and confirmed that the elements in table1 are of unicode type so the error message does not make any sense to me. Perhaps it is just not possible to write unicode to csv files?
Any advice is highly appreciated.