python读取csv指定列_使用python读取csv中的特定列

def read_csv(file, columns, type_name="Row"):

try:

row_type = namedtuple(type_name, columns)

except ValueError:

row_type = tuple

rows = iter(csv.reader(file))

header = rows.next()

mapping = [header.index(x) for x in columns]

for row in rows:

row = row_type(*[row[i] for i in mapping])

yield row

例:

>>> import csv

>>> from collections import namedtuple

>>> from StringIO import StringIO

>>> def read_csv(file, columns, type_name="Row"):

... try:

... row_type = namedtuple(type_name, columns)

... except ValueError:

... row_type = tuple

... rows = iter(csv.reader(file))

... header = rows.next()

... mapping = [header.index(x) for x in columns]

...

你可能感兴趣的:(python读取csv指定列)