I am learning Python and trying to understand writing to a CSV. I need it to be in a header / row set up and keep getting a float error

Question:

import csv

FILENAME = "trip.csv"

def save_data(miles, gallons, mpg):
    header = ["Distance", "Gallons", "MPG"]
    data = [miles, gallons, mpg]
    with open(FILENAME, 'w', newline="") as file:
        writer = csv.writer(file)
        writer.writerow(header)
    with open(FILENAME, 'a', newline="") as file:
        writer = csv.writer(file)
        writer.writerows(data)

def display_title():
    print("The Miles Per Gallon program.n")


def calculate_totals(miles, gallons, cost):
    mpg = miles / gallons
    cost_per_mile = miles / cost
    total_fuel_cost = gallons * cost
    display_data(mpg, cost_per_mile, total_fuel_cost, gallons, miles)

def display_data(mpg, cost_per_mile, total_fuel_cost, gallons, miles):
    print()
    print(f"MPG on this trip is {mpg} gallons.")
    print(f"Cost per mile was ", cost_per_mile)
    print(f"Total fuel spent was ", total_fuel_cost)
    print()
    save_data(miles, gallons, mpg)

def main():
    display_title()
    
    choice = "y"
    while choice.lower() == "y":
        miles = float(input("Enter miles driven: "))
        gallons = float(input("Enter gallons used: "))
        cost = float(input("Enter cost per gallon: "))
        calculate_totals(miles, gallons, cost)
        choice = input("Do you wish to enter a new entry: y/n ")

if __name__ == "__main__":
    main()

enter image description here

I was trying to get an output into a CSV that had Distance, Gallons and MPG as a header with the rows underneath keeping user input data. I finally figured out how to make the header but now I am getting a float error and nothing I try seems to get rid of it. Any help would be appreciated.

Asked By: Timothy Easter

||

Answers:

The problem is that you are using writerows on the second call, which expects an iterable of iterables of values, whereas you’re only passing it an iterable of values. There’s two ways to fix it:

  1. Use writerow:
writer.writerow(data)
  1. Actually pass in an iterable of iterables, most easily by creating another list:
writer.writerows([data,])
Answered By: RoadieRich
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.