Home > Back-end >  How to convert a string containing several float numbers into an array of float in Python?
How to convert a string containing several float numbers into an array of float in Python?

Time:09-10

I have a text file which contains float characters line by line as

    15.723
    17.567

I tried reading the file and after doing this

with open('<path_to_file>/writefile.txt', 'r') as fin:
    data_read = fin.read()

When I print data_read, I get

'15.723\n17.567\n'

Now I need to save this string into an array containg

float_array[0]=15.723
float_array[1]=17.567

How do I do the conversion?

I tried

print(float(data_read))
res = data_read.astype(float)
print(res)

And I got

ValueError: could not convert string to float: '15.723\n17.567\n'

What am I doing wrong here?

I am expecting something like float_array[0]=15.723 float_array[1]=17.567

CodePudding user response:

You can read the file directly into a list of strings (using readlines()) and then convert every line to float. So you don't have to use split()

with open('<path_to_file>/writefile.txt', 'r') as fin:
    data_read = fin.readlines()
numbers = list(map(float, data_read))

CodePudding user response:

First split your string into individual numbers:

list_of_strings = data_read.split()

Now you can apply float to each element:

list_of_floats = [float(x) for x in list_of_strings if x]

The check if x discards the last empty element if your file ends with a newline. If it doesn't, you can do

list_of_floats = list(map(float, list_of_strings))

Or you can strip the data first:

list_of_strings = data_read.strip().split()
  • Related