Question

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

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?)
Enquirer: ap306

||

Solution #1:

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.

Respondent: Aaron Hall

Solution #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:
Respondent: Garren S

The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 .

Most Popular

To Top
India and Pakistan’s steroid-soaked rhetoric over Kashmir will come back to haunt them both clenbuterol australia bossier man pleads guilty for leadership role in anabolic steriod distribution conspiracy