19

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?)
0

2 Answers 2

15

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.

Sign up to request clarification or add additional context in comments.

2 Comments

will this work for Python 3 version
@anj yes, yes it will.
2

The solution in this (duplicate?) question csv.Error: iterator should return strings, not bytes helped me:

f = open('Address Book.csv', "rt")

or

with open('Address Book.csv', "rt") as f:

or (using gzip)

import gzip
f = gzip.open('Address Book.csv', "rt")

or

import gzip
gzip.open('Address Book.csv', "rt") as f:

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.