2013-06-05 5 views
7

열 이름이 대문자 인 CSV 파일이 있습니다. csv.dictreader를 사용하여 데이터를 읽고 있지만 소문자로 열 이름이 필요합니다.Python dictreader - CSV 열 이름을 소문자로 만드는 방법은 무엇입니까?

내가 발견 여기에이 코드 Accessing csv header white space and case insensitive

import csv 

class DictReaderInsensitive(csv.DictReader): 
    # This class overrides the csv.fieldnames property. 
    # All fieldnames are without white space and in lower case 

    @property 
    def fieldnames(self): 
     return [field.strip().lower() for field in super(DictReaderInsensitive, self).fieldnames] 

    def __next__(self): 
     # get the result from the original __next__, but store it in DictInsensitive 

     dInsensitive = DictInsensitive() 
     dOriginal = super(DictReaderInsensitive, self).__next__() 

     # store all pairs from the old dict in the new, custom one 
     for key, value in dOriginal.items(): 
      dInsensitive[key] = value 

     return dInsensitive 

class DictInsensitive(dict): 
    # This class overrides the __getitem__ method to automatically strip() and lower() the input key 

    def __getitem__(self, key): 
     return dict.__getitem__(self, key.strip().lower()) 

내 문제는 내가

datafile = open(self.ifs_data_file,'rU') 
     csvDict = DictReaderInsensitive(datafile) 
     for row in csvDict: 
      print row 
      #self.db.ifs_data.insert(**row) 
      #self.db.commit() 

이것을 실행할 때이 오류

Traceback (most recent call last): 
    File "D:\Development\python\supplier_review\supplier_review.py", line 239, in update_ifs_data 
    for row in csvDict: 
    File "D:\Python27_5\lib\csv.py", line 103, in next 
    self.fieldnames 
    File "D:\Development\python\supplier_review\supplier_review.py", line 288, in fieldnames 
    return [field.strip().lower() for field in super(DictReaderInsensitive, self).fieldnames] 
TypeError: must be type, not classobj 

답변

7

DictReader를 얻을 수 있다는 것입니다 옛날 스타일 개체이므로 여기에서 super()이 전혀 작동하지 않습니다. 부모 클래스의 property 개체에 직접 액세스해야합니다.

class DictReaderInsensitive(csv.DictReader): 
    # This class overrides the csv.fieldnames property. 
    # All fieldnames are without white space and in lower case 

    @property 
    def fieldnames(self): 
     return [field.strip().lower() for field in csv.DictReader.fieldnames.fget(self)] 

    def next(self): 
     return DictInsensitive(csv.DictReader.next(self)) 

데모 :

>>> example = '''\ 
... foo,Bar,BAZ 
... 42,3.14159,Hello world!'''.splitlines() 
>>> csvDict = DictReaderInsensitive(example) 
>>> row = next(csvDict) 
>>> print row 
{'bar': '3.14159', 'foo': '42', 'baz': 'Hello world!'} 
>>> row['BAZ'] 
'Hello world!' 
+0

의견을 보내 주셔서 감사합니다. 나는이 문제를 해결하기 위해 또 다른 방법을 찾았지만 정직하기는 그것이 무엇인지 기억하지 못한다. 나는 Martijn 's를 시험해 보았다. 그러나 그것은 나를 위해 일하지 않았다. – PrestonDocks

+2

죄송합니다. 내 솔루션이 도움이되지 않았습니다. 어떤 문제가 발생했는지 알려주셨습니까? 아마도 내가 당신을 극복하는 데 도움이되었을 것입니다. 내 대답에서 알 수 있듯이 코드를 테스트했습니다. –

5

당신은 DictReader에 전달하기 전에 파일의 첫 번째 줄을 소문자 수 :

import csv 
import itertools 

def lower_first(iterator): 
    return itertools.chain([next(iterator).lower()], iterator) 

with open(ifs_data_file, 'rU') as datafile: 
    csvDict = csv.DictReader(lower_first(datafile)) 
    for row in csvDict: 
     print row  
파이썬 2에서는 .next() 방법이 아닌 .__next__()을 대체하려면
+0

4 년 후, 이것은 여전히 ​​유용하고 구현하기 쉬운 기술입니다. – scottwed

2

훨씬 간단한 접근 방법으로 다음과 같이 사전에 액세스하기 전에 DictReader.fieldnames 속성을 간단히 업데이트 할 수 있습니다.

>>> f = open('example-x-y-time.csv', 'rb') 
>>> reader = csv.DictReader(f) 
>>> reader.fieldnames 
['Latitude', 'Longitude', 'Date'] 
>>> print next(reader) 
{'Latitude': '44.8982391', 'Date': '2004-07-12', 'Longitude': '-117.7791061'} 
>>> reader.fieldnames = [name.lower() for name in reader.fieldnames] 
>>> print next(reader) 
{'latitude': '44.6637001', 'date': '1964-04-03', 'longitude': '-123.5997009'} 
관련 문제