_csv.Error:迭代器应返回字符串,而不是字节(您是否以文本模式打开文件?) [英] _csv.Error: iterator should return strings, not bytes (did you open the file in text mode?)

查看:280
本文介绍了_csv.Error:迭代器应返回字符串,而不是字节(您是否以文本模式打开文件?)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的csv程序开始时:

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

错误是:

    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(),因为它会在发生错误或退出上下文时自动关闭文件.

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.

这篇关于_csv.Error:迭代器应返回字符串,而不是字节(您是否以文本模式打开文件?)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆