【问题标题】:_csv.Error: iterator should return strings, not bytes (did you open the file in text mode?) [duplicate]_csv.Error:迭代器应返回字符串,而不是字节(您是否以文本模式打开文件?)[重复]
【发布时间】:2014-03-02 19:08:17
【问题描述】:

在我的 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?)

【问题讨论】:

    标签: python csv


    【解决方案1】:

    代替这个(以及其他):

    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 3 版本
    • @anj 是的,是的。
    【解决方案2】:

    这个(重复?)问题csv.Error: iterator should return strings, not bytes 中的解决方案帮助了我:

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

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

    或(使用 gzip)

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

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

    【讨论】:

      猜你喜欢
      • 2013-09-24
      • 2020-12-17
      • 2023-01-22
      • 2018-03-24
      • 2020-05-06
      • 1970-01-01
      • 2016-04-07
      • 2021-03-21
      相关资源
      最近更新 更多