Python How to convert file data into float data

1.3k Views Asked by At

I'm trying to convert the data inside a file to be read as float numbers. It is a very large file. It won't let me convert it because it says it is a list. How do I fix this?:

    File = open(filename,'r')
    for line in File:
        Data = File.readlines()
        for line in Data:
                numData = float(Data)
    File.close()
2

There are 2 best solutions below

0
On
for line in Data:
    numData = float(Data)

That's where your problem is. You're calling float() on the list Data instead of on the element line.

Incidentally, you seem to be looping twice over the file when you don't have to. You declare File, then iterate over it, and for each iteration, you're rereading it -- and iterating over it again. You should probably do something more like this:

with open(filename, 'r') as file:
    for line in file:
        numData = float(line)

Of course, I doubt that you really mean to set numData (which should be called num_data according to PEP8, IIRC) every time. I don't know what it's meant to be used as, though, because the variable name is unclear, so I can't tell you what you should do instead. If it's a list, you probably mean something like this:

with open(filename, 'r') as file:
    for line in file:
        num_data.append(float(line))

Note that I changed numData to num_data.

0
On

This is one way to do it:

file_lines = [float(ln.rstrip()) for ln in open(filename)]