In Python, how do I search a flat file for the closest match to a particular numeric value?

Posted by kaushik on Stack Overflow See other posts from Stack Overflow or by kaushik
Published on 2010-06-09T17:24:01Z Indexed on 2010/06/09 18:22 UTC
Read the original article Hit count: 163

Filed under:
|

have file data of format

3.343445 1  
3.54564 1  
4.345535 1  
2.453454 1

and so on upto 1000 lines and i have number given such as a=2.44443 for the given file i need to find the row number of the numbers in file which is most close to the given number "a" how can i do this i am presently doing by loading whole file into list and comparing each element and finding the closest one any other better faster method?

my code:i need to ru this for different file each time around 20000 times so want a fast method

p=os.path.join("c:/begpython/wavnk/",str(str(str(save_a[1]).replace('phone','text'))+'.pm'))
        x=open(p , 'r')
        for i in range(6):
            x.readline()

        j=0
        o=[]
        for line in x:

            oj=str(str(line).rstrip('\n')).split(' ')
            o=o+[oj]

            j=j+1


        temp=long(1232332)
        end_time=save_a[4]

        for i in range((j-1)):
            diff=float(o[i][0])-float(end_time)
            if diff<0:
                diff=diff*(-1)
            if temp>diff:
                temp=diff
                pm_row=i

© Stack Overflow or respective owner

Related posts about python

Related posts about beginner