0

I'm reading german names from a csv, and want to write them in a csv file, with the right encoding for ä, ö and ü. Reading works fine, but when I write to the csv, the characters are displayed like this: Löffler.

reader1 = csv.reader(open('names.csv', 'rb'), delimiter=',')

What do I need to add to my writer to get the right encoding?

    outfile.write('K:' + n + ',' + a + ',' + '-' + '\n')

I tried unicodecsv, but can't get it to work:

w = unicodecsv.writer(outfile, encoding='utf-8')
w.write('K:' + n + ',' + a + ',' + '-' + '\n')

Error message:

AttributeError: 'UnicodeWriter' object has no attribute 'write'
MJP
  • 5,327
  • 6
  • 18
  • 18

2 Answers2

1

In python2.X your best bet is using tool like unicodecsv, as csv module in this python handles only acsii.

On Python3+ you'll get this ot of the box, just pass proper encoding to the open function.

jb.
  • 23,300
  • 18
  • 98
  • 136
  • Please look into csv module API, this module allows you to write rows of data (that is arrays) using `writer.writerow` function, while you are trying to write line by hand. – jb. Jan 21 '14 at 13:11
  • This worked, however, encoding still doesn't work! Can you point me to an easy example of how to use unicodecsv with csv writer? – MJP Jan 21 '14 at 13:16
  • You need to use `unicodecsv` both to read and write the csv file. Encoding might get lost at any point. Please post working example of your code, I might spot problems. – jb. Jan 21 '14 at 13:50
0

I think you must change the encoding of the file. I think UTF-8 should work. Do you use Java? Here someone showed how it should work.

Community
  • 1
  • 1