Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading from CSV: delimiter must be a string, not unicode

Tags:

python

csv

django

I had a working routine (after a few helpful folks gave me some critical advice in this thread) creating model instances from a CSV file. Up to now I have been using Python 2.7 and made sure no special characters appeared anywhere. Currently I need to move to Unicode. I added

# -*- coding: utf-8 -*-

at the top of my files and everything is working nicely (I can use special characters in my code and comments), save for the CSV reader routine. Namely, the shell objects to this part:

dataReader = csv.reader(open(filename), delimiter=';', quotechar='"')

which was working before, with

TypeError: "delimiter" must be string, not unicode

After reading some older questions I switched to

dataReader = csv.reader(open(filename), delimiter=str(u';'), quotechar=str(u'"'))

to enforce the fact that the delimiter would be a string, but I'm getting exactly the same error. What am I doing wrong?

like image 951
Leszek Wroński Avatar asked Nov 28 '16 10:11

Leszek Wroński


2 Answers

Your default encoding is probably not the most appropriate.

Specify the encoding like this :

dataReader = csv.reader(open(filename), delimiter=str(u';').encode('utf-8'), quotechar=str(u'"').encode('utf-8'))
like image 176
Chr Avatar answered Sep 18 '22 06:09

Chr


Happened to me when I switched the code from a file without from __future__ import unicode_literals to one that had it. (python 2.7)

It changed the default encoding for string and messed with the existing code.

Fixed it by changing from:

# worked before using unicode_literals
writer = csv.writer(csvfile, delimiter=';', quotechar='"')  

to

# worked when using unicode_literals
writer = csv.writer(csvfile, delimiter=str(';'), quotechar=str('"'))  
like image 38
Vadorequest Avatar answered Sep 21 '22 06:09

Vadorequest