csv.Error: iterator should return strings, not bytes csv.Error: iterator should return strings, not bytes python-3.x python-3.x

csv.Error: iterator should return strings, not bytes


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.


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 csvifile  = open('sample.csv', "rb")read = csv.reader(ifile)for row in read :    print (row) 

New code:

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


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 csvimport codecsifile  = open('sample.csv', "rb")read = csv.reader(codecs.iterdecode(ifile, 'utf-8'))for row in read :    print (row)