我正在尝试使用 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/