-5

I am trying to pull out all the relevant info for the lines with the minimum value in a csv file with Python. Below is my code to find out the relevant information. The minimum value is 12 when I code it spaerately. But when I put in the function and will process the minimum to find and record other data in the csv file.The value can not be updated. What I am missing to update the value of line[9]?

The CVS file contains a column of numbers and I need to find the minimum. The separate coding works well to find the minimum of 12 and I did it as a test. But it does not work after I assign a function and use the same method to find the minimum. As I need to use the minimum in other part of the code, it is better if I can put it in the function and make it work. So I would like to know how should transfer the function also works in finding the minimum. Thank you in advance.

#put finding minimum in to a function and will use the returned minimum 
#to pull out other information    
def findMin():  
minMile = 100
if num<minMile:
    minMile=num
return minMile


def main():
    fileIn = open("epaVehicleData2008.csv", "r")
    fileIn.readline()
    for line in fileIn:
        line = line.split(",")
        num=int(line[9])
        findmin(line)
        minMile=int(line[9])
        print(minMile)


main()

#separate code for finding the minimum as a test
fileIn = open("epaVehicleData2008.csv", "r")
fileIn.readline()
minMile = 100
for line in fileIn:
    line = line.split(",")
    num = int(line[9])
    if num < minMile:
        minMile = num
print(minMile)
  • where exactly are you updating the value? all I see you doing is reading the same file twice one time using a function and the other time doing the same exact process without a function, what is the desired output – eagle Mar 05 '18 at 00:09

1 Answers1

0

This can be done using Python's CSV library to help with reading each line and automatically splitting it in a list:

import csv

def findMin(filename):
    with open(filename, 'r', newline='') as f_input:
        csv_input = csv.reader(f_input)
        return min(csv_input, key=lambda x: int(x[9]))[9]

print('Min mile', findMin('epaVehicleData2008.csv'))

The built-in min() function can be used to determine the smallest row. It takes a key parameter which tells it which part of the input you want to compare with, in this case the 9th element.

Each time you call your findMin(), the value for minMile will always be 100. In your design, you would need to make the variable global, rather than local to your function. Perhaps a better approach would be to pass the function a filename and let it read and calculate the minimum in one go and return that value.

lambda is just a function written inline without needing a separate def. In this case, it takes x being a row, and returns the ninth value as an integer.

Martin Evans
  • 45,791
  • 17
  • 81
  • 97