あなたは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}]
残念ながら、これはまだヘッダーに窒息します。 –
まさに私が探していたもの、ありがとう! – MoRe