. Advertisement .
..3..
. Advertisement .
..4..
Recently, I ran some of my python code, and it gave the warning text:
for row in reader: # iterates the rows of the file in orders
_csv.Error: iterator should return strings, not bytes (did you open the file in text mode?)
While searching, I realized that some people added some command lines in my sample above. But I don’t think it is the best way to correct the problem – iterator should return strings, not bytes (did you open the file in text mode?) How would you explain this trouble? or Is there a better way? Below is the detail of the command that I used:
import csv # imports the csv module
import sys # imports the sys module
f = open('Address Book.csv', 'rb') # opens the csv file
try:
reader = csv.reader(f) # creates the reader object
for row in reader: # iterates the rows of the file in orders
print (row) # prints each row
finally:
f.close() # closing
The cause: You don’t need the
finally: f.close()
, because it will automatically close the file on an error, or on exiting the context.Solution:
Instead of this (and the rest):
Do this:
It is throwing an exception because you have
rb
as your argument, which opens the file with binary mode. You can change that tor
which will open the file in text mode .Use this code:
Code new: