0

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):

  1. adding encoding='utf-8' as argument in the open(filename) method
  2. adding 'import unicodecsv as csv' to my script
  3. importing io and changing open(filename) into io.open(filename)
  4. 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.

Oswin
  • 1
  • 1
  • 1
    The error message's line number doesn't correspond to the shown code. Can you make sure the error message and the code shown belong together, especially when you've already "tried a lot"? – deceze Jun 01 '20 at 10:53
  • 2
    If you're just starting out, I'd strongly suggest you pick up Python 3 if at all possible. Python 2.7 reached [end-of-life](https://www.python.org/doc/sunset-python-2/) this January. – Ronald Jun 01 '20 at 10:53
  • 2
    This is a duplicate, your answer awaits here: https://stackoverflow.com/a/24221963/4765315 – Ronald Jun 01 '20 at 11:00
  • 1
    I believe Python 2 required the file to be open in binary mode for the csv module. – Mark Ransom Jun 01 '20 at 19:54
  • Thanks for the comments. In the end I figured it out and solved it by going back to open() instead of io.open() and removing the 'u' in front of the strings. The special comment lines on top seem to have done it. The encoding is now latin-1 which for now seems to be working out for the data that I am importing and need to store. Probably utf-8 encoding would even be better since it allows even more characters but I will leave that for later. – Oswin Jun 01 '20 at 21:11
  • I already have installed python3 a few days ago but I ran into unexpected problems with ssl certificate validation stuff for the other part of my code. I am not prepared yet to deal with that but surely I will have step up to python3 soon ;-) – Oswin Jun 01 '20 at 21:17

0 Answers0