You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python读取CSV两列数据到两个列表失败问题排查

问题原因与解决方法

你的问题出在csv.reader返回的是迭代器——迭代器只能被遍历一次,第一个循环已经把文件里的所有行都读完了,第二个循环再去遍历的时候,迭代器已经没有剩余数据了,所以julytemp列表是空的。

正确写法:单循环同时读取两列

不需要分开两个循环,在同一个循环里就能同时把两列数据存入对应的列表:

import csv
with open('matplotlibexperiments\Weather Data in India from 1901 to 2017.csv') as file:
    csvreader = csv.reader(file)
    
    header_row = next(csvreader)
    years = []
    julytemp = []   

    # 一次循环同时处理两列
    for row in csvreader:
        years.append(row[1])
        julytemp.append(row[7])
    
    print(years)
    print(julytemp)

额外优化(可选)

如果后续需要频繁按列访问数据,也可以用csv.DictReader,通过列名来获取数据,这样更直观,不用记索引:

import csv
with open('matplotlibexperiments\Weather Data in India from 1901 to 2017.csv') as file:
    # 用列名作为键来读取数据
    csvreader = csv.DictReader(file)
    years = []
    julytemp = []   

    for row in csvreader:
        # 替换成你CSV里实际的年份列名和七月气温列名
        years.append(row['YEAR'])
        julytemp.append(row['JULY'])
    
    print(years)
    print(julytemp)

内容的提问来源于stack exchange,提问作者theunbugger

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.16 10:09:54