_csv.Error:迭代器应该返回字符串,而不是字节(你是否在文本模式下打开文件?)

ap3*_*306 17 python csv

在我的csv计划开始时:

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
Run Code Online (Sandbox Code Playgroud)

错误是:

    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?)
Run Code Online (Sandbox Code Playgroud)

Aar*_*all 13

而不是这个(和其余的):

f = open('Address Book.csv', 'rb')
Run Code Online (Sandbox Code Playgroud)

做这个:

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

上下文管理器意味着您不需要finally: f.close(),因为它会在出错时自动关闭文件,或者在退出上下文时自动关闭文件.