I have a text file. inside there is text like that (no header):
1,2,5,7
I’m trying to get the the closest number to 3, but higher than 3. the answer would be 5.
with open("myfile.txt", "r") as f:
lines = f.read()
num = float("10")
print(min(filter(lambda x: x > num, lines)))
It doesn’t work, it seems there a problem with the list or strings or array.
When I do it like this it works:
num = 3
li = [1,2,5,7]
print (min(filter(lambda x: x > num,li)))
I tried to write it like this [1,2,5,7] in myfile.txt, it’s not working. f.read() and f.readlines() also not working.
>Solution :
This task screams for numpy
import numpy as np
fin = 'myfile.txt'
num = 2
a = np.loadtxt(fin, delimiter=',')
b = np.sort(a)
c = b[b > num][0]
print(c)