gpt4 book ai didi

python - 从 CSV 文件中读取特定行

转载 作者:行者123 更新时间:2023-12-02 17:36:48 34 4
gpt4 key购买 nike

我有一个十行的 CSV 文件。从这个文件中,我只想要第四行。最快的方法是什么?我正在寻找类似的东西:

with open(file, 'r') as my_file:
reader = csv.reader(my_file)
print reader[3]

reader[3] 显然是我想要实现的不正确语法。如何将阅读器移动到第 4 行并获取其内容?

最佳答案

如果只有 10 行,则可以将整个文件加载到列表中:

with open(file, 'r') as my_file:
reader = csv.reader(my_file)
rows = list(reader)
print rows[3]

对于更大的文件,使用 itertools.islice() :

from itertools import islice

with open(file, 'r') as my_file:
reader = csv.reader(my_file)
print next(islice(reader, 3, 4))

关于python - 从 CSV 文件中读取特定行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26197189/

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