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 got the following exception

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

How can i fix this?

+69
Dec 15 '11 at 4:18
source share
4 answers

You open the file in text mode.

More specific:

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

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

+108
Dec 15 '11 at 11:22
source share

I just fixed this problem with my code. The reason this exception is because you have an rb argument. Change it to r .

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) 
+36
Mar 10 '15 at 21:27
source share

You have a problem with b in open . The rt flag (read, text) is the default, so using the context manager, just do the following:

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

The context manager means that you do not need general error handling (without which you can get stuck in opening a file, especially in the interpreter), because it will automatically close the file when an error occurs or when you exit the context.

The above value is the same as:

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

or

 with open('sample.csv', 'rt') as ifile: ... 
+9
Feb 12 '15 at 21:44
source share

I had this error while running an old python script developed using Python 2.6.4

When upgrading to 3.6.2, I had to remove all "rb" parameters from open calls in order to fix this csv read error.

+3
Jul 31 '17 at 18:30
source share



All Articles