gpt4 book ai didi

python - 使用 DictReader 从 csv 文件中获取第一条记录

转载 作者:太空宇宙 更新时间:2023-11-04 00:24:43 26 4
gpt4 key购买 nike

我正在尝试使用 DictReader 从 csv 文件中获取第一条记录作为字典。我无法理解,因为文档只谈论迭代读者对象

 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)

关于python - 使用 DictReader 从 csv 文件中获取第一条记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47907505/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com