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

CSV文件读取异常问题:为何代码仅能正确读取第一组数据到列表,后续数据无法读取?

问题原因及解决方案

嘿,这个问题我太熟悉啦!问题出在csv.reader返回的是一个迭代器,它只能被遍历一次。你第一次用列表推导式lats = [row[0] for row in reader]的时候,已经把所有行都读完了,后面再去遍历reader获取lons和brightness时,迭代器里已经没有任何数据了,所以这两个列表自然是空的。

另外还要提一句:你代码里忘记导入csv模块了,这个一定要补上,不然运行会直接报错哦!

修复方案有两种,你可以选适合自己的:

方案一:先把所有行一次性读取到列表中

先把整个CSV的行都存到一个列表里,之后再从这个列表里提取需要的数据,这样就不会出现迭代器耗尽的问题:

from plotly.graph_objs import Scattergeo, Layout
from plotly import offline
import csv  # 补上缺失的csv模块导入

filename = 'data/MODIS_C6_1_Global_24h.csv'
with open(filename) as f:
    reader = csv.reader(f)
    header_row = next(reader)
    print(header_row)
    # 先把所有行读取到列表中
    rows = list(reader)
    # 再从rows里提取数据
    lats = [row[0] for row in rows]
    lons = [row[1] for row in rows]
    brightness = [row[2] for row in rows]

print(lats)
print(lons)
print(brightness)

方案二:在一次遍历中同时收集三个数据

这种方法更高效,不需要额外存储所有行,只需要遍历一次就能把三个数据都收集好:

from plotly.graph_objs import Scattergeo, Layout
from plotly import offline
import csv  # 补上缺失的csv模块导入

filename = 'data/MODIS_C6_1_Global_24h.csv'
with open(filename) as f:
    reader = csv.reader(f)
    header_row = next(reader)
    print(header_row)
    
    lats = []
    lons = []
    brightness = []
    # 一次遍历,同时给三个列表添加数据
    for row in reader:
        lats.append(row[0])
        lons.append(row[1])
        brightness.append(row[2])

print(lats)
print(lons)
print(brightness)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.29 14:44:07