Reading floats from a file using python

My input file is of the form:

5.0, 1000.0, 100000000000000.0, 115.2712, 230.538, 345.796, 461.0408, 
1.053E-09, 1.839E-09, 1.632E-10, 1.959E-12, 4.109, 3.683, 3.586, 3.650 

      

where each number is essentially on a string.

What I want to do is read all the floats and then add only columns 7 to 10 to the array.

Here's what I wrote:

T=[]
with open("test.txt", "r") as file1:
    for line in file1.readlines():
        f_list = [float(i) for i in line.split(",")]
        T.append(float(f_list[7]))
        T.append(float(f_list[8]))
        T.append(float(f_list[9]))
        T.append(float(f_list[10]))

      

When I run the above, I get:

ValueError: could not convert string to float:

      

I think there is something wrong with the part float(i)

, but I cannot find a way to get around it.

I've seen people with similar problems here, but none of the fixes I've tried so far have helped. Any help is appreciated.

+3


source to share


2 answers


No problem with your first line ending with a comma :

5.0, 1000.0, 100000000000000.0, 115.2712, 230.538, 345.796, 461.0408,
1.053E-09, 1.839E-09, 1.632E-10, 1.959E-12, 4.109, 3.683, 3.586, 3.650 

      

As a result, you want to process a string that contains spaces (for example ' '

). And float(' ')

fails as it is not a number (it does report it):

>>> float(' ')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: could not convert string to float: 
>>> float('a')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: could not convert string to float: 'a'

      

But when you print, the space is simply invisible.

You can solve this problem by adding a filter expression to the list:



T = []
with open("test.txt", "r") as file1:
    for line in file1.readlines():
        f_list = [float(i) for i in line.split(",") if i.strip()]
        T += f_list[7:11]
      

Also, it wo n't , since none of the rows float 7-11 . Therefore, you will never add these floats.

However, you can use the following code:

with open("test.txt", "r") as file1:
    f_list = [float(i) for line in file1 for i in line.split(',') if i.strip()]
    T = f_list[7:11]

      

This will result in the T

following being:

>>> T
[1.053e-09, 1.839e-09, 1.632e-10, 1.959e-12]

      

+4


source


Your problem is that when you split line

, the resulting list most likely contains spaces. This will result in an error float()

. First you need to misinform your split list by checking if the item is indeed a valid floating point number. eg:



>>> def is_float(n):
    try:
        float(n)
        return True
    except:
        return False


>>> 
>>> line = '5.0, 1000.0, 100000000000000.0, 115.2712, 230.538, 345.796, 461.0408,'
>>> lst = [float(n) for n in line.split(',') if is_float(n)]
>>> lst
[5.0, 1000.0, 100000000000000.0, 115.2712, 230.538, 345.796, 461.0408]
>>>

      

+2


source







All Articles