繁体   English   中英

Python在csv.DictReader()中返回KeyError

[英]Python returns KeyError in csv.DictReader()

我是python(2.x)上的新程序,甚至连数小时我都无法解决问题。 Python返回KeyError

(object).csv文件为:

id,name,type
1,low,player

python代码是:

import csv

class Item(object):

    def setup(self, config):
        self.config = config
        self.label = config['label']
        self.name = config['name']
        self.type = config['type']
def create_item(config):
    new_item = Item()
    new_item.setup(config)
    return(new_item)

def populate():
    all_items = {}
    f = open('object.csv', 'rb')
    reader = csv.DictReader(f, delimiter = ',')
    for row in reader:
        new_item = (create_item(row))
        all_items[new_item.label] = new_item 
    return(all_items)

Python返回:

Self.type = config['type']
KeyError: 'type'

奇怪的是,在csv和python代码中,列标题均不包含任何键入错误。 当我更改“ id”列的名称时,错误返回到新标题(以前为“ id”)。 (当我添加另一个标题并尝试读取它时,也会发生同样的情况)

欢迎任何帮助,不便之处,敬请原谅。 感激

 class Item(object):

      def setup(self, config):
          self.config = config
          self.id = config['id']
          self.name = config['name']
          self.type = config['type']

  def create_item(config):
          new_item = Item()
          new_item.setup(config)
          return(new_item)
  def populate():
          all_items = {}
          f = open('test.txt', 'r')
          reader = csv.DictReader(f, delimiter = ',')
          for row in reader:
              new_item = (create_item(row))
              all_items[new_item.id] = new_item
          return(all_items)

输出:

things = populate()
things.keys()
dict_keys(['1'])

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM