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

问题描述 投票:1回答:2

我试图使用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]?

python csv
2个回答
1
投票

因为你可以迭代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)

1
投票

要获得没有for循环的CSV的第一行:

with open(filename, 'r', newline='') as f:
    r = csv.reader(f, delimiter=',')
    return next(r)

当然,如果你有一排标题,你必须“跳过”它:

with open(filename, 'r', newline='') as f:
    r = csv.reader(f, delimiter=',')
    _ = next(r) # hold header row in throwaway variable
    return next(r)

上下文管理器中的newline=''用于Python3 +(也许是Python2的更高版本),但对于Python2.7.8及更早版本,您可以省略。

© www.soinside.com 2019 - 2024. All rights reserved.