Finding minimum in a column from .csv without using python module

Viewed 77

I am creating a program that can help me find the minimum value in a column from a .csv file. However, before I can do this, I am struggling to sort the data into a list. Here is what I have done:

#open the file
csv_file = open("test_data.csv","r")
#print out all values in the last second column
for data in csv_file:
    data = data.replace("\n","").split(",")[-2]
    print(data)

This is what I get:

27
24
33
52
54
53

However, I would like to sort them in this way so I can use the min() function to find the minimum.

[27,24,33,52,54,53]

Any advice would be greatly appreciated thank you. :)

2 Answers

Why append to a list at all? Just get the minimum.

#open the file
csv_file = open("test_data.csv","r")
#print out all values in the last second column
results = []

for i, data in enumerate(csv_file):
    data = data.replace("\n","").split(",")[-2]
    if i == 0:
        minimum = data
    if data < minimum:
        minimum = data

print(minimum)

First create a list and then append the values.

#open the file
csv_file = open("test_data.csv","r")
#print out all values in the last second column
results = []
for data in csv_file:
    data = data.replace("\n","").split(",")[-2]
    print(data)
    results.append(data)
print(min(results))



Related