我正在尝试使用 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)
Run Code Online (Sandbox Code Playgroud)
是否有任何函数可以将第一条记录作为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)
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
6935 次 |
最近记录: |