2017-02-20 8 views
0

저는 파이썬 (2.x)에서 새로운 프로그래밍을하고 있으며 문제를 해결할 수없는 몇 시간 동안 찾고 있습니다.파이썬은 csv.DictReader()에서 KeyError를 반환합니다.

id,name,type 
1,low,player 

파이썬 코드는 다음과 같습니다 :

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) 

파이썬은 반환

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

이상한 일을 파이썬은 KeyError를

(객체) .CSV 파일이를 반환 csv와 python 코드에서 열 머리글에 입력 오류가 없다는 것입니다. "id"열의 이름을 변경하면 오류가 새 헤더 (이전의 "id")로 반환됩니다. (다른 헤더를 추가하여 읽을 때도 마찬가지입니다.)

불편을 끼쳐 드려 죄송합니다. 감사

+0

당신은 쉼표 주위에 여분의 공간이있다. 'create_item'을 호출하기 전에 행을 인쇄 해보십시오. – niemmi

+0

여분의 공백은 내 실수로 게시물을 입력하는 것입니다. 미안합니다. '{'id ':'1 ','name ':'낮음 ','유형 ':'플레이어 '}'하지만 그 후에 오류가 지속됩니다. –

+0

[예외 잡기] (https://docs.python.org/3/tutorial/errors.html#handling-exceptions) 예외 제품군에서'''row'''는 예상 한 키입니까? – wwii

답변

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

출력 : 실제 열 이름 ''ID '', ''이름 '`&`type'` 그래서

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

이 출력은 나를 반환합니다 : File "items.py", 33 행을 채우고 f = open ('files/object.csv', 'rb') RuntimeError : Python 객체를 호출하는 동안 최대 재귀 심도를 초과했습니다. 그것은 –

+0

입니다. f = open ('files/object.txt', 'r')과 동일합니다. [all_items [new_item.id]]에 대해 all_items [new_item.label]을 바꿔도 같습니다. –

+0

@LeandroPeres, 1. 이것은 다른 오류이므로 문제가 해결되었습니다. 2. 새로운 문제는 이미 여기에서 논의되었습니다. http://stackoverflow.com/questions/14222416/recursion-in-python-runtimeerror-maximum-recursion-depth-exceeded-while-callin – gregory