2014-03-02 2 views
10

Zu Beginn meines csv-Programm:_csv.Error: Iterator sollte Strings zurückgeben, nicht Bytes (haben Sie die Datei im Textmodus öffnen?)

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 

Und der Fehler ist:

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

Antwort

9

Statt dessen (und der Rest):

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

tun:

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

Der Kontextmanager bedeutet, dass Sie die finally: f.close() nicht benötigen, da die Datei bei einem Fehler oder beim Beenden des Kontextes automatisch geschlossen wird.

2

Die Lösung in diesem (duplizieren?) Frage csv.Error: iterator should return strings, not bytes mir geholfen:

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

oder

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

oder (mit gzip)

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

oder

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