3 回答

TA贡献1784条经验 获得超2个赞
您可以将文件的第一行小写,然后再传递给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

TA贡献1785条经验 获得超8个赞
DictReader是一个老式的对象,因此super()在这里根本无法使用。您需要直接访问property父类中的对象。在Python 2中,您要覆盖.next()方法,而不是.__next__():
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!'

TA贡献1797条经验 获得超4个赞
对于更简单的方法,您可以在访问字典之前简单地更新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'}
添加回答
举报