user1094976
user1094976

Reputation:

csv.Error: iterator should return strings, not bytes

Sample.csv contains the following:

NAME    Id   No  Dept
Tom     1    12   CS
Hendry  2    35   EC
Bahamas 3    21   IT
Frank   4    61   EE

And the Python file contains the following code:

import csv
ifile  = open('sample.csv', "rb")
read = csv.reader(ifile)
for row in read :
    print (row) 

When I run the above code in Python, I get the following exception:

File "csvformat.py", line 4, in for row in read : _csv.Error: iterator should return strings, not bytes (did you open the file in text mode?)

How can I fix it?

Upvotes: 206

Views: 350172

Answers (8)

hchakroun
hchakroun

Reputation: 1

You need to change the open mode to text. I came upon this on the documentation, and this example is not working:

https://docs.python.org/3.11/library/collections.html#namedtuple-factory-function-for-tuples-with-named-fields :

EmployeeRecord = namedtuple('EmployeeRecord', 'name, age, title, department, paygrade')
import csv
for emp in map(EmployeeRecord._make, csv.reader(open("employees.csv", "rb"))):
    print(emp.name, emp.title)

Upvotes: 0

abduljalil
abduljalil

Reputation: 153

You can do something like this in django

import csv
import io
csv_file = = open('sample.csv', "rb")
file = csv_file.read().decode('utf-8')
csv_reader = csv.DictReader(io.StringIO(file))
for row in csv_reader:
    print(row)

Upvotes: 1

MagicLAMP
MagicLAMP

Reputation: 1072

This is a GOTCHA in Django. The open that comes with filefield always opens the file in byte mode as far as I can tell. You need to open with Python's open instead.

So with avccont_datafile being an instance of a model with a field called datafile = django.db.models.FileField(), The following code....

with avccount_datafile.datafile.file.open('rt') as fp:
    self.avc_data = csv.DictReader(fp)

gives the error

_csv.Error: iterator should return strings, not bytes (did you open the file in text mode?)

but this fixes it

filename = avccount_datafile.datafile.file.name
with open(filename, 'rt') as fp:
        self.avc_data = csv.DictReader(fp)

Upvotes: 3

MMM
MMM

Reputation: 1211

The reason it is throwing that exception is because you have the argument rb, which opens the file in binary mode. Change that to r, which will by default open the file in text mode.

Your code:

import csv
ifile  = open('sample.csv', "rb")
read = csv.reader(ifile)
for row in read :
    print (row) 

New code:

import csv
ifile  = open('sample.csv', "r")
read = csv.reader(ifile)
for row in read :
    print (row)

Upvotes: 121

Grigoriy Mikhalkin
Grigoriy Mikhalkin

Reputation: 5573

In Python3, csv.reader expects, that passed iterable returns strings, not bytes. Here is one more solution to this problem, that uses codecs module:

import csv
import codecs
ifile  = open('sample.csv', "rb")
read = csv.reader(codecs.iterdecode(ifile, 'utf-8'))
for row in read :
    print (row) 

Upvotes: 50

Michael Fayad
Michael Fayad

Reputation: 1336

I had this error when running an old python script developped with Python 2.6.4

When updating to 3.6.2, I had to remove all 'rb' parameters from open calls in order to fix this csv reading error.

Upvotes: 11

Aaron Hall
Aaron Hall

Reputation: 395045

Your problem is you have the b in the open flag. The flag rt (read, text) is the default, so, using the context manager, simply do this:

with open('sample.csv') as ifile:
    read = csv.reader(ifile) 
    for row in read:
        print (row)  

The context manager means you don't need generic error handling (without which you may get stuck with the file open, especially in an interpreter), because it will automatically close the file on an error, or on exiting the context.

The above is the same as:

with open('sample.csv', 'r') as ifile:
    ...

or

with open('sample.csv', 'rt') as ifile:
    ...

Upvotes: 33

Lennart Regebro
Lennart Regebro

Reputation: 172249

You open the file in text mode.

More specifically:

ifile  = open('sample.csv', "rt", encoding=<theencodingofthefile>)

Good guesses for encoding is "ascii" and "utf8". You can also leave the encoding off, and it will use the system default encoding, which tends to be UTF8, but may be something else.

Upvotes: 251

Related Questions