您可以使用 pandas 之类的库,它会为您推断类型(这有点矫枉过正,但可以完成工作)。
import pandas
data = pandas.read_csv(r'..\data\data.csv')
# if you just want to retrieve the first column as a list of int do
list(data.Col1)
>>> [1, 90]
# to convert the whole CSV file to a list of dict use
data.transpose().to_dict().values()
>>> [{' Col2': 2, ' Col3': 3, 'Col1': 1}, {' Col2': 2, ' Col3': 3, 'Col1': 90}]
另外,这里是一个类型化 DictReader 的实现:
from csv import DictReader
from itertools import imap, izip
class TypedDictReader(DictReader):
def __init__(self, f, fieldnames=None, restkey=None, restval=None, \
dialect="excel", fieldtypes=None, *args, **kwds):
DictReader.__init__(self, f, fieldnames, restkey, restval, dialect, *args, **kwds)
self._fieldtypes = fieldtypes
def next(self):
d = DictReader.next(self)
if len(self._fieldtypes) >= len(d) :
# extract the values in the same order as the csv header
ivalues = imap(d.get, self._fieldnames)
# apply type conversions
iconverted = (x(y) for (x,y) in izip(self._fieldtypes, ivalues))
# pass the field names and the converted values to the dict constructor
d = dict(izip(self._fieldnames, iconverted))
return d
这里是如何使用它:
reader = TypedDictReader(open('..\data\data.csv'), dialect='excel', \
fieldtypes=[int, int, int])
list(reader)
>>> [{' Col2': 2, ' Col3': 3, 'Col1': 1}, {' Col2': 2, ' Col3': 3, 'Col1': 90}]