I am writing a program that extracts the minimum and maximum MPG rating for cars. The car's information is stored in a CSV file. I believe I wrote the correct min/max functions, however, I wrote it as if I was looping through all of the rows/columns.

We are only supposed to include certain categories of cars for data extraction. The category of a car is the first column of CSV data, which has an index of [0]. The MPG rating I am looping through is in column 10, which has an index of [9].

We are not supposed to include the categories "van", "minivan" or "trucks" in our min/max MPG calculation. Is there a way to exclude based on these strings and loop through the remaining MPGs that are not excluded?

Lastly, once this is accomplished, I am supposed to write these results to a new file. Is there any way I can open the file being written, to check if my code works?

When I try to print the contents of the newly created file (based on user input), I get an error saying that file is not in the directory. Any help would be appreciated.

NOTE: We are not allowed to import Pandas.

Current Code:

print("Welcome to EPA Mileage Calculator")
yearChoice = int(input("What year would you like to view data for? (2008 or 2009): "))
while yearChoice != 2008 and yearChoice != 2009:
    print("Invalid input, please try again")
    yearChoice = int(input("What year would you like to view data for? (2008 or 2009): "))
saveResults = input("Enter the filename to to save results to: ")

if yearChoice == 2008:
    fileIn = open("epaVehicleData2008.csv", "r")
    fileIn.readline()
    minMPG, maxMPG = [], []
    for line in fileIn:
        line = line.strip()
        dataList = line.split(",")
        minMPG.append(line[9])
    print(min(minMPG))
    print(max(maxMPG))

if yearChoice == 2009:
    fileIn = open("epaVehicleData2009.csv", "r")
    fileIn.readline()
    minMPG, maxMPG = [], []
    for line in fileIn:
        line = line.strip()
        dataList = line.split(",")
        minMPG.append(line[9])
    print(min(minMPG))
    print(max(maxMPG))

fileIn = open(saveResults, "r")
for line in fileIn:
    print(line)

1 Answers

1
Bill the Lizard On Best Solutions

First, you have a bug in the two spots in your code like this:

line = line.strip()
dataList = line.split(",")
minMPG.append(line[9])

In the third line, you're getting the value line[9]. That's the character at index 9 in the line, not the value at index 9 of the list. Do minMPG.append(dataList[9]) instead.

Next, you can check that the vehicle type is not in a specific group using an if statement. Something like

if dataList[9] not in ['van', 'truck', 'minivan']:
    minMPG.append(dataList[9])

For your last problem, you haven't saved anything in saveResults yet, or created the file, so it makes sense that you get an error when you try to read it. There are a lot of questions and answers on how to do that. Look to some of those, and ask a separate question if you can't get your code to work.