gpt4 book ai didi

python - 从指定位置读取数据

转载 作者:行者123 更新时间:2023-11-28 18:08:52 24 4
gpt4 key购买 nike

import CSV

#Get high temperatures from file.
filename = 'sitka_weather_07-2014.csv'
with open(filename) as f:
reader = csv.reader(f)
header_row = next(reader)

highs = []
for row in reader:
highs.append(row[1])

print(highs)

我在学习提取和读取数据时遇到了上面的代码。

我不太明白 next() 的用法:

header_row = next(reader)

书上解释说,因为我们已经读取了标题行,所以循环将从实际数据开始的第二行开始

如果我们需要从第三行开始读怎么办?以下是正确的吗?

with open(filename) as f:
reader = csv.reader(f)
header_row = next(reader)
row_1 = next(reader)

highs = []
for row in reader:
highs.append(row[2])

Print(highs)

这个问题可能很无聊,但我很困惑

最佳答案

下一个函数将光标向前移动一行,所以在代码段中是

header_row = next(reader)
row_1 = next(reader)
highs = []
for row in reader:
highs.append(row[2])
Print(highs)

虽然这不是最好的方式,但该行确实从第三行开始。

如果你想直接访问行,试试这个

with open(filename) as f:
reader = csv.reader(f)
rows = list(reader)
print rows[2] # this will get you the third row

关于python - 从指定位置读取数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51943596/

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