1

I'm trying to fill some floaty values from a file into a tuple with the following python code:

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   

The values originate from a .csv-file, where lines look like this:

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

The problem is I get:

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

ValueError: could not convert string to float: 

And I have no idea whats wrong. Please illumiate me.

Tybald
  • 167
  • 1
  • 1
  • 12

2 Answers2

0

This probally means what is says. Your variable s is a string which is not a float. You could try adding this snippet to print/find your problematic string.

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

See also a similiar question: https://stackoverflow.com/a/8420179/4295853

Dominik
  • 241
  • 2
  • 12
  • Thank you very much! The last two lines of the file look also different. I ignored that and your code hinted me the problem. Stupid me =) – Tybald May 03 '18 at 09:01
-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}
Nic
  • 3,365
  • 3
  • 20
  • 31
  • This doesn't answer the question. You simply rewrote the asker's code with no functional difference. He asker even admitted the error was in the format of the file. – Reti43 May 03 '18 at 11:11