Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Get the the closest higher number from a text file

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading