csv.Error: iterator should return strings, not bytes
Hire the world's top talent on demand or became one of them at Toptal: https://topt.al/25cXVn
and get $2,000 discount on your first invoice
--------------------------------------------------
Take control of your privacy with Proton's trusted, Swiss-based, secure services.
Choose what you need and safeguard your digital life:
Mail: https://go.getproton.me/SH1CU
VPN: https://go.getproton.me/SH1DI
Password Manager: https://go.getproton.me/SH1DJ
Drive: https://go.getproton.me/SH1CT
Music by Eric Matyas
https://www.soundimage.org
Track title: Breezy Bay
--
Chapters
00:00 Csv.Error: Iterator Should Return Strings, Not Bytes
00:39 Accepted Answer Score 251
01:02 Answer 2 Score 33
01:40 Answer 3 Score 121
02:05 Answer 4 Score 11
02:22 Thank you
--
Full question
https://stackoverflow.com/questions/8515...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python #python3x #csv
#avk47
ACCEPTED ANSWER
Score 251
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.
ANSWER 2
Score 121
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)
ANSWER 3
Score 33
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:
...
ANSWER 4
Score 11
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.