float from numbers in text file

davidgp davidvanijzendoorn at gmail.com
Mon Jun 21 20:38:01 EDT 2010


On Jun 21, 5:13 pm, Stephen Hansen <me+list/pyt... at ixokai.io> wrote:
> On 6/21/10 4:26 PM, davidgp wrote:
>
>
>
>
>
> > ah, i see :P
> > float("45.34") or whatever does work fine, but the problem is that i'm
> > reading it from a text file. so somehow it is not a real string or
> > whatever..
> > here's a part of the code:
> > f = open ('/home/david/out.txt', 'r')
>
> > for line in f:
> > if tel ==6:
> >                    buf = line.replace('\n', '')
> >                    lat = float(buf)
> >            if tel ==7:
> >                    buf = line.replace('\n', '')
> >                    lng = float(buf)
>
> > basically it goes wrong in the last part where i try to convert the
> > line to a float..
> > i'm 100% sure that it's getting a number, not a text string
>
> First: you don't have to strip \n's. Try float("45.43\n")
>
> Second: this code, as is, can't run to show us the problem because
> there's this "tel" business and I don't know what it is. But I'll tweak
> it a bit and:
>
>   f = open ('/Users/ixokai/out.txt', 'r')
>
>   tel = 6
>   for line in f:
>      if tel == 6:
>         buf = line.replace('\n', '')
>         lat = float(buf)
>         print lat
>      if tel == 7:
>         buf = line.replace('\n', '')
>         lng = float(buf)
>
> And it works fine with a dummy data file I have. So... the problem is
> somewhere else. Its either in your data file, or some other logic going
> on (maybe something related to this 'tel' thing, I don't know).
>
> Are you sure there's no lines in out.txt which have, say, some text (on
> the left end)? Or maybe some blank lines?
>
> Maybe you should send the whole file and the data.txt if you don't see
> where the problem is.
>
> --
>
>    Stephen Hansen
>    ... Also: Ixokai
>    ... Mail: me+list/python (AT) ixokai (DOT) io
>    ... Blog:http://meh.ixokai.io/
>
>  signature.asc
> < 1KViewDownload

i found the error! apparently something was going wrong in the loop..
thanks for the help!



More information about the Python-list mailing list