无法将字符串从inputfile转换为float

时间:2018-05-03 08:52:16

标签: python string types numbers double

我正在尝试使用以下python代码将文件中的一些浮点值填充到元组中:

with open(filename, 'r') as file:

    i=0
    lines = file.readlines()            
    for line in lines:
        if (line != None) and (i != 0) and (i != 1):        #ignore first 2 lines
            splitted = line.split(";")

            s = splitted[3].replace(",",".")

            lp1.heating_list[i-2] = float(s)    
         i+=1   

值来自.csv文件,其中的行如下所示:

MFH;0:15;0,007687511;0,013816233;0,023092447;

问题是我得到了:

lp1.heating_list[i-2] = float(s)

ValueError: could not convert string to float: 

我不知道什么是错的。请照亮我。

2 个答案:

答案 0 :(得分:0)

这可能意味着说什么。您的变量<Container />是一个不是浮点数的字符串。 您可以尝试添加此代码段以打印/查找有问题的字符串。

s

另见类似问题:https://stackoverflow.com/a/8420179/4295853

答案 1 :(得分:-1)

from io import StringIO

txt = """ligne1
ligne2
MFH;0:15;0,007687511;0,013816233;0,023092447;
MFH;0:15;0,007687511;0,013816233;0,023092447;
MFH;0:15;0,007687511;0,013816233;0,023092447;
MFH;0:15;0,007687511;0,013816233;0,023092447;
"""

lp1_heating = {}

with StringIO(txt) as file:
    lines = file.readlines()[2:] # ignore first 2 lines 
    for i, line in enumerate(lines):            
            splitted = line.split(";")            
            s = splitted[3].replace(",",".")
            lp1_heating[i] = float(s)  

print(lp1_heating )
{0: 0.013816233, 1: 0.013816233, 2: 0.013816233, 3: 0.013816233}