Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

_csv.Error: iterator should return strings, not bytes (did you open the file in text mode?) [duplicate]

Tags:

python

csv

At the start of my csv program:

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

And the error is:

    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?)
like image 619
ap306 Avatar asked Mar 02 '14 19:03

ap306


1 Answers

Instead of this (and the rest):

f = open('Address Book.csv', 'rb')

Do this:

with open('Address Book.csv', 'r') as f:
    reader = csv.reader(f) 
    for row in reader:
        print(row)  

The context manager means you don't need the finally: f.close(), because it will automatically close the file on an error, or on exiting the context.

like image 184
Russia Must Remove Putin Avatar answered Sep 20 '22 12:09

Russia Must Remove Putin