Reputation: 1
I have a problem with a command of python. I want my program to read a specific line from my file, and here I haven't problem. The problem is when I have to convert the line in a float (I need of float to calculate some equation). My program is:
f=open('coeff.txt')
lines=f.readlines()
k1=lines[0]
k1 = float(k1)
k2=lines[1]
k2 = float(k2)
k3=lines[2]
k3 = float(k3)
k4=lines[3]
k4 = float(k4)
And the file coeff.txt is:
1.2*1e-1
6.00*1e-34
1.13*1e-4
6.9*1e-16
that is 1.2*10^(-1) , 6*10^(-34), 1.13*10^(-4), 6.9*10^(-16)
and I get the error:
ValueError: could not convert string to float: '6.00*1e-34\n'
(obviously that this error is referred to each line.
Can you help me, please?
Upvotes: 0
Views: 1631
Reputation: 815
Python doesn't know how to interpret '6.00*1e-34\n'
as a float. You will have to clean your data before you can actually use it.
Eventually, you will want to have each line in a format like this:
6.00e-34
Looking at it closely, it seems like the only differences are the \n
at the end of the line, and the 1*
in the middle.
You can get rid of the newline character at the end of the string (\n
) by calling the .strip()
method, and replace *1
with an empty string to get to the above format.
val = '6.00*1e-34\n'
cleaned_val = val.strip().replace('*1', '')
print(float(cleaned_val))
>>> 6e-34
Edit: It seems like the presence of the newline character doesn't really matter - so you only need to replace the *1
part of your string. I'm leaving it in anyway.
Upvotes: 2