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

2024-09-27 07:26:46 发布

您现在位置:Python中文网/ 问答频道 /正文

我尝试用以下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: 

我不知道怎么了。请照亮我。你知道吗


Tags: and文件代码withlineopenfloatfilename
2条回答
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}

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

try:
    lp1.heating_list[i-2] = float(s) 
except ValueError:
    print("tried to convert {} on line {}".format(s, i))

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

相关问题 更多 >

    热门问题