Use:
Data = namedtuple("Data", next(reader))
and omit the line:
next(reader)
Combining this with an iterative version based on martineau's comment below, the example becomes for Python 2
import csv
from collections import namedtuple
from itertools import imap
with open("data_file.txt", mode="rb") as infile:
reader = csv.reader(infile)
Data = namedtuple("Data", next(reader)) # get names from column headers
for data in imap(Data._make, reader):
print data.foo
# ...further processing of a line...
and for Python 3
import csv
from collections import namedtuple
with open("data_file.txt", newline="") as infile:
reader = csv.reader(infile)
Data = namedtuple("Data", next(reader)) # get names from column headers
for data in map(Data._make, reader):
print(data.foo)
# ...further processing of a line...
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…