Reputation: 537
I have *.txt
file, which contains data like this:
...
30 5.882973099631601
31 6.035463584639685
32 6.184276444600495
33 6.3336851616329435
34 6.492617147379082
35 6.683538372963013
36 6.841228384748939
37 6.999432758805214
...
Now I would like to find the minimum value (second column), but I'd like to display it with value from the first column. So in that case I'd like to print this row, as a minimum function and it suppose to look like this:
30 5.882973099631601
I've been trying to do this with that code, but I'm stuck.
with open('measurements.txt', 'a') as j:
j.write(str(r))
j.write(" ")
j.write(line[24:])
j.write('\n')
j.close()
Upvotes: 0
Views: 2438
Reputation: 1305
import csv
# preparing data - converting to array
rows = []
with open('sample.txt', mode='r') as infile:
reader = csv.reader(infile, delimiter=" ")
for row in reader: # each row is a list
rows.append(row)
# lambda function to filter min considering the second column
minimus = min(rows, key=lambda x: float(x[1]))
# done
print(minimus)
Upvotes: 1
Reputation: 178
For getting the row with minimum value:
min_row = ''
min_val = 1000000 # Considering this value to be the highest
'''
Loop for reading rows in source file
'''
a, b = row.split(' ')
b = float(b)
if b < min_val:
min_val = b
min_row = row
'''
End of loop
'''
Then, write 'min_row' in the new file.
Upvotes: 0