• Register
0 votes
3.7k views

 Problem :

MySample.csv contains the below details :

NAME    Id    No  Dept
Tommy    1    12   CS
Jimmy    2    35   EC
Bonny    3    21   IT
Franky   4    61   EE

And my Python file contains the below code :

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

But when I try to run the above code in Python, I get the below 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 should I fix it?

7.5k points

Please log in or register to answer this question.

1 Answer

0 votes

Solution :

You need to open your file in text mode.

More specifically refer below line of code :

myifile  = open('mysample.csv', "rt", encoding=<theencodingofthefile>)

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

OR

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

import csv
import codecs
myifile  = open('mysample.csv', "rb")
read = csv.reader(codecs.iterdecode(myifile, 'utf-8'))
for row in read :
print (row)
38.6k points