你可以使用像熊貓這樣的圖書館,它會推斷你的類型(這有點矯枉過正,但它的工作)。
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}]
不幸的是,這仍然會窒息頭。 – 2012-01-05 19:52:08
正是我在找什麼,謝謝! – MoRe 2014-12-08 18:06:48