David
David

Reputation: 173

How to convert a string into a float when reading from a text file

Hey guys so I have a text file that I am trying to read from and receive every number string and convert it into a float. But every time I try it, it says "cannont convert string to float". Why is this happening? Thanks!

try:
    input_file = open("Dic9812.TFITF.encoded.txt","r")
    output_fileDec = open("Dic9812.TFITF.decoded.txt","w")
    output_fileLog = open("Dic9812.TFITF.log.txt","w")
except IOError:
    print("File not found!")

coefficientInt = input("Enter a coefficient: ")
coefficientFl = float(coefficientInt)
constInt = input("Enter a constant: ")
constFl = float(constInt)

try:
    for line in input_file:
        for numstr in line.split(","):
            numFl = float(numstr)
            print(numFl)
except Exception as e:
    print(e)

The file looks like this:

135.0,201.0,301.0
152.0,253.0,36.0,52.0
53.0,25.0,369.0,25.0

It ends up printing the numbers but at the end it says: cannot convert string to float:

Upvotes: 0

Views: 7889

Answers (2)

user1907906
user1907906

Reputation:

Input f

135.0,201.0,301.0
152.0,253.0,36.0,52.0
53.0,25.0,369.0,25.0

Python f.py

import sys

for line in sys.stdin.readlines():
    fs = [float(f) for f in line.split(",")]
    print fs

Usage

$ python f.py < f

Output

[135.0, 201.0, 301.0]
[152.0, 253.0, 36.0, 52.0]
[53.0, 25.0, 369.0, 25.0]

Upvotes: 0

Maxime Lorant
Maxime Lorant

Reputation: 36161

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 input_file:
    for numstr in line.split(","):
        if numstr:
            try:
                numFl = float(numstr)
                print(numFl)
            except ValueError as e:
                print(e)

As said in comments, avoid to catch Exception and try to have the minimum lines of code in a try/except to avoid silent errors.

Upvotes: 5

Related Questions