Invalid literal for float(): 0.000001, how to fix error?

偶尔善良 提交于 2019-12-07 17:33:45

问题


I have a .csv file containing 3 columns of data. I need to create a new output file that includes a specific set of data from the first and third column from the original file. The third column contains decimal values, and I believe in such a case I have use the float() feature of python. I have tried the following code:

in_file = open("filename.csv", "r")

out_file = open("output.csv", "w")

while True:

    line = in_file.readline()
    if (line == ''): 
        break
    line = line.strip() 
    items = line.split(',') 
    gi_name = items[0] 
    if (gi_name.startswith("_"))
        continue
    p_value = float(items[2]) 
    if (p_value > 0.05):
        continue
    out_file.write(','.join([gene_name, str(p_value)]))
in_file.close()
out_file.close()

when I run the above, I recieve the following error:

Error: invalid literal for float(): 0.000001

the value 0.0000001 is the first value in my data set for the third column, and I guess the code cannot read beyond that set but I'm not sure why. I am new to python, and don't really understand why I am getting this error or how to fix it. I have tried other modifications for how to input the float(), but without success. Does anyone know how I might be able to fix this?


回答1:


From what you've posted, it's not clear whether there is something subtly wrong with the string you're trying to pass to float() (because it looks perfectly reasonable). Try adding a debug print statement:

print(repr(items[2]))
p_value = float(items[2])

Then you can determine exactly what is being passed to float(). The call to repr() will make even normally invisible characters visible. Add the result to your question and we will be able to comment further.




回答2:


Your file most likely has some unprintable character that is read. Try this:

>>> a = '0.00001\x00'
>>> a
'0.00001\x00'
>>> print(a)
0.00001
>>> float(a)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: invalid literal for float(): 0.00001

You can see that a has a NUL character which is not printed with either print or the exception of float.



来源:https://stackoverflow.com/questions/9917294/invalid-literal-for-float-0-000001-how-to-fix-error

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!