【问题标题】:Error: iterator should return strings, not collections.OrderedDict (did you open the file in text mode?)错误:迭代器应该返回字符串,而不是 collections.OrderedDict(您是否以文本模式打开文件?)
【发布时间】:2020-05-06 17:34:23
【问题描述】:
import numpy as np
import csv
from PIL import Image
import pandas as pd

counter = dict()

with open('train.csv', 'r') as csv_file: 
    csv_reader = csv.reader(csv_file, delimiter=',', quotechar='"')

# skip headers
next(csv_reader)

for row in csv.reader(csv_reader):

    pixels = row[:-1] # without label
    pixels = np.array(pixels, dtype='uint8')
    pixels = pixels.reshape((28, 28))
    image = Image.fromarray(pixels)

    label = row[-1]

    if label not in counter:
        counter[label] = 0
    counter[label] += 1

    filename = '{}{}.jpg'.format(label, counter[label])
    image.save(filename)

    print('saved:', filename)

我有这段代码,正如帖子的标题所说,由于该错误,我无法读取 CSV 文件。我已经尝试了所有可能的阅读模式。任何想法?我是 mac 用户,我正在使用 python 2.7,以防万一。谢谢。

【问题讨论】:

  • for row in csv_reader: - 无需再次阅读
  • 另外,整个块应该在with 语句中,以保证您在关闭文件之前处理它。
  • 另外,您可能会在此处收到错误消息:label = row[-1]

标签: python csv


【解决方案1】:

你已经在这里读过一次文件了:

with open('train.csv', 'r') as csv_file: 
    csv_reader = csv.reader(csv_file, delimiter=',', quotechar='"')

你可以直接使用,无需再次拨打csv.reader(...)

for row in csv.reader(csv_reader):

改成:

for row in csv_reader:

【讨论】:

  • reader 实际上并没有读取文件;它是一个围绕文件对象的包装器,当有人从包装器中读取时,它将从文件中读取。
  • 这是真的……真是个错误。谢谢。
猜你喜欢
  • 2018-03-24
  • 2023-01-22
  • 2020-12-17
  • 1970-01-01
  • 1970-01-01
  • 2016-04-07
  • 2021-03-21
  • 2013-09-24
相关资源
最近更新 更多