저는 파이썬 (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")로 반환됩니다. (다른 헤더를 추가하여 읽을 때도 마찬가지입니다.)
불편을 끼쳐 드려 죄송합니다. 감사
당신은 쉼표 주위에 여분의 공간이있다. 'create_item'을 호출하기 전에 행을 인쇄 해보십시오. – niemmi
여분의 공백은 내 실수로 게시물을 입력하는 것입니다. 미안합니다. '{'id ':'1 ','name ':'낮음 ','유형 ':'플레이어 '}'하지만 그 후에 오류가 지속됩니다. –
[예외 잡기] (https://docs.python.org/3/tutorial/errors.html#handling-exceptions) 예외 제품군에서'''row'''는 예상 한 키입니까? – wwii