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

Python 3.9读取CSV文件时仅输出最后一行数据问题求助

解决CSV数据打印只显示最后一行的问题

嘿,很高兴帮你搞定这个小问题!我仔细看了你的代码,一下子就找到问题所在啦~

问题根源

你在遍历CSV行的时候,每次都会把foods变量重新赋值为当前行的食物名称,循环结束后foods自然就只保留了最后一行的内容。但其实你已经把所有行的数据都存在data列表里了,只是打印的时候没用到这个列表而已!

修改后的完整代码

我帮你调整了代码,不仅能打印所有数据,还优化了文件操作的方式:

import csv
path = "stuff/foods.csv"

# 用with语句自动管理文件,不用手动关闭
with open(path, newline='') as file:
    reader = csv.reader(file)
    header = next(reader)
    data = []
    for row in reader:
        # 解析每行数据并添加到data列表
        foods = str(row[0])
        serving_size = int(row[1])
        calories = int(row[2])
        carbs = int(row[3])
        fat = int(row[4])
        protien = int(row[5])
        fiber = int(row[6])
        data.append([foods, serving_size, calories, carbs, fat, protien, fiber])

user_input = ""
while user_input.lower() != "quit":
    user_input = input("Would you like the menu?: ").lower()
    if user_input == "yes":
        # 遍历data列表,打印所有食物数据
        print("=== 食物菜单 ===")
        for item in data:
            foods, serving_size, calories, carbs, fat, protien, fiber = item
            print(f"- {foods}: 份量{serving_size},热量{calories}大卡,碳水{carbs}g,脂肪{fat}g,蛋白质{protien}g,纤维{fiber}g")
    elif user_input == "quit":
        print("拜拜~")
        break

关键修改点

  1. 使用with语句操作文件:这是Python处理文件的最佳实践,它会在代码块结束后自动关闭文件,避免资源泄漏。
  2. 遍历data列表打印所有数据:当用户输入yes时,不再只打印单个foods变量,而是循环遍历data里的每一条记录,把所有食物信息都输出出来。

这样修改后,你再运行代码输入yes,就能看到CSV里的所有食物数据啦!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.30 08:12:40