2013-06-05 27 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  
のPython 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'} 
関連する問題