我正在尝试使用 DictReader 从 csv 文件中获取第一条记录作为 dict。我无法理解,因为文档只讨论迭代阅读器对象
with open(filename, 'r') as f_in:
# Use the csv library to set up a DictReader object.
trip_reader = csv.DictReader(f_in)
# Use a function on the DictReader object to read the
# first trip from the data file and store it in a variable.
for row in trip_reader:
pprint(row)
是否有任何函数可以将第一条记录作为trip_reader [0]?
最佳答案
由于您可以遍历 trip_reader
,因此您可以对其调用 next()
以获取下一行(在本例中为第一行):
with open(filename, 'r') as f_in:
# Use the csv library to set up a DictReader object.
trip_reader = csv.DictReader(f_in)
# Use a function on the DictReader object to read the
# first trip from the data file and store it in a variable.
row = next(trip_reader)
pprint(row)