【问题标题】:(Python) Printing only the last line in row from a CSV file and I want the entire row with all the lines(Python) 仅打印 CSV 文件中的最后一行,并且我想要包含所有行的整行
【发布时间】:2021-08-30 11:18:26
【问题描述】:

大家好,我是编码新手,正在尝试我的第一个项目,但我遇到了问题。在导入我的 csv 并读取行后,我将所有单独的行附加到一个变量中,但是当我打印出该变量时,它只给出该行中的最后一行,我需要该行中的所有行。我会很感激一些帮助。下面是我在 python 3.9 中的代码

import csv

path = "stuff/foods.csv"
file = open(path, newline='') 
reader = csv.reader(file)  

header = next(reader)
data = []
for row in reader:
    # row = [Foods, Serving_Size, Calories, Carbs, Fat, Protien, Fiber]
    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":
        print(foods)
    elif user_input == "quit":
        break    

【问题讨论】:

    标签: python python-3.x csv


    【解决方案1】:

    好吧,对于 csv 中的每一行,您都会覆盖变量 foods,因此当您在最后打印它时,它会打印最后一个值。

    您将信息保存在名为data 的列表中,因此要打印所有信息,您需要该列表。我认为这对你有用:

    import csv
    
    path = "stuff/foods.csv"
    file = open(path, newline='') 
    reader = csv.reader(file)  
    
    header = next(reader)
    data = []
    for row in reader:
        # row = [Foods, Serving_Size, Calories, Carbs, Fat, Protien, Fiber]
        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":
            for i in data:
                print(i[0])
        elif user_input == "quit":
            break    
    

    另外,您使用file = open(path,newline='') 打开文件,但我没有看到您关闭它。这样做是一种很好的做法,并且有一种使用 with 的标准 Pythonic 方式。您可以了解更多here

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-04-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-06-15
      • 1970-01-01
      • 2020-09-07
      • 2020-02-23
      相关资源
      最近更新 更多