python - _csv.Error : iterator should return strings, not bytes(您是否以文本模式打开文件?)

标签 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

错误是:

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

最佳答案

代替这个(以及其他):

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

这样做:

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

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

关于python - _csv.Error : iterator should return strings, not bytes(您是否以文本模式打开文件?),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22132034/

相关文章:

csv - 如何在PIG中将XLSX文件转换为CSV文件?

javascript - 在 c3.js 中从 csv 文件创建分类条形图

python - python中请求之间的适当时间?

python - FileNotFoundError 在使用 Python 的 AWS Lambda 上出现前导斜线问题

python - (python)在运行时生成和执行代码是否被认为是不好的做法?

csv - Google BigQuery 不解析可为空的第二个时间戳字段

Python matplotlib 绘制具有多个值的字典

python - 从 QThread 生成并插入到 QTreeWidget 中的 QWidget 的正确父子关系

mysql - CSV,将多行转换为按另一列值分组的逗号分隔列表

python - CSV 在单个 csv 字段中的单个列表中写入多个项目