Reading a text file and converting string to float

python read float from file
convert string to float python
could not convert string to float
python read numbers from file
python read float array from text file
python read file
parse text file python
python list comprehension file read

I have a text file called "foo.txt", with a list of numbers, one on each line, for example:

0.094195
0.216867
0.326396
0.525739
0.592552
0.600219
0.637459
0.642935
0.662651
0.657174
0.683461

I now want to read these numbers into a Python list. My code to do this is as follows:

x = []
file_in = open('foo.dat', 'r')
for y in file_in.read().split('\n'):
    x.append(float(y))

But this gives me the error:

ValueError: could not convert string to float

What am I doing wrong?


Edit:

commented by martineau: you can also use if y: to eliminate None or empty string.

Original Answer:

It fails due to you are using newline character as a separator, therefore the last element is empty string

you can add y.isdigit() to check whether y is numeric.

x = []
file_in = open('sample.csv', 'r')
for y in file_in.read().split('\n'):
    if y.isdigit():
        x.append(float(y))

OR

you can change read().split("\n") to readlines()

OR

remove the leading/trailing characters from y. it handles the lines with extra whitespaces

for y in file_in:
    trimed_line = y.strip()  # leading or trailing characters are removed

How to convert a string into a float when reading from a text file , At the end of the second line, you have a comma, so you have an empty string in the list. float('') raise an exception, hence your error: for line in  Python CSV formatting with string and float and write How do you format a float to 2 decimal points with mixed data type? I'm fetching a table and writing rows to csv file. My data is (string, string, float, float, float) sql = 'select * from testTable' c.execute(sql) columnNames = list(map(lambda x:


How about this approach:

x = []
with open('foo.dat', 'r') as f:
    for line in f:
        if line: #avoid blank lines
            x.append(float(line.strip()))

Or:

with open('foo.dat', 'r') as f:
    lines = (line.strip() for line in f if line)
    x = [float(line) for line in lines]

Finally more compact:

with open('foo.dat', 'r') as f:
    x = [float(line.strip()) for line in lines if line]

This way you don't have to worry about blank lines and you make proper conversion from string to float

[PDF] Reading data from a file Example: reading a file with numbers (part , We can read text in the file into strings in a program load all lines into a list of strings (lines): For each word after the first: if word is not "no", convert to float. csv.QUOTE_NONNUMERIC: Instructs the reader to convert all non-quoted fields to type float. That works if you're ok with all unquoted fields (integer, float, text, Boolean etc.) being converted to float, which is generally a bad idea for many reasons (missing or NA values in Booleans or factors will get silently squelched).


Usually files has empty line at the end so probably you're trying to cast empty string to float.

Instead of file_in.read().split('\n') you could use:

for line in file_in.readlines():
  x.append(float(line))

Method readlines returns list of all lines from given file and skips last empty line if present.

Reading a file line by line, Before trying to let a program read a file, we must know the file format, i.e., what the The reason is that lines holds each line ( number ) as a string, not a float or int that we can add to other numbers. A fix is to convert each line to a float :. Usually files has empty line at the end so probably you're trying to cast empty string to float. Instead of file_in.read().split(' ') you could use: for line in file_in.readlines(): x.append(float(line)) Method readlines returns list of all lines from given file and skips last empty line if present.


You can try using the default float function

>>> float("1.1")
1.1

You could also try using the python try else statement which will run the code until it catches a error and runs a else statement.

try:
   try_this(whatever that might bring up a error)
except SomeException as exception:
   #Handle exception
else:
   return something

There might be a possibility that there is a blank line end of the file which might create errors. Try using the try else statement because of it.

C# Need to change a string to Float. (read from text file then sort , it works (sort of) it sorts the text document properly but it doesnt take into account negative numbers. this is why i need to convert the string to a float. if someone  Reading from a .txt file to a pandas dataframe. I'm reading the text file to store it in a dataframe by doing: and then uses that to convert all the other rows.


I think You string like this : '0.1111, 0.1111' or other

file_in = open('foo.dat', 'r')
for y in file_in.readlines()[0]:
    x.append(float(y))

Python Convert String to float, If we are getting float value from user input through the terminal or reading it from a file, then they are string objects. So we have to explicitly convert them to float  SSIS keeps force changing excel source string to float. Is it possible to get the file as a .csv file which can be imported like a text file and will not have


Using strings from text file as input for float variable., You can then convert strings to floats using float(). So there are only a I've advised you to make a separate function to read the file into vars[]. Need help converting a string to a float converting strings to most their efficient types '1' --> 1, 'A' ---> 'A', '1.2'---> 1.2; Code refactoring: Reading string data from file and converting the data type; Help converting this Write to operator<< overload; Converting String to Float; Converting a hexidecimal string to a floating point


Python:Reading (int,float,comp,bool) from file, Homework Statement Read a comma separated numeric (int, float, comp, bool) values from a file and store each comma That is if float value is there in file then it cannot be typecasted to int. But we have to sort, so we have to convert it into numeric type. This is storing the list contents in string format. I am attempting to put integers from a text file to an array. I am new to C. I have already found the number of lines and opened the file. I do not understand why this does not work: I want to scan all the numbers into array z[] except for the first one. I would paste my whole program attempt, but


Data Types and Conversion, You have seen: int (integer), float (floating-point number), str (string), list (list), to enter this bar' Traceback (most recent call last): File "<pyshell#71>", line 1,