Search code examples
python-3.9

ValueError: could not convert string to float: 'Setup..\r\n'


I want to run my code using Arduino and Python. I have to write a script to fetch the data serially and save it into a CSV file. When I run the script I get this error "ValueError: could not convert string to float: 'Setup..\r\n'"

  import csv
  from time import time
  import serial 
  import numpy
  # Your serial port might be different!

  ser = serial.Serial('COM12',baudrate=9600, bytesize=8, timeout=1)

  f = open("df.csv", "a+")
  writer = csv.writer(f, delimiter=',')
  while True:
    s = ser.readline().decode()
    if s != "":
      rows = [float(x) for x in s.split(',')]
      # Insert local time to list's first position
      rows.insert(0, int(time()))
      print(rows)
      writer.writerow(rows)
      f.flush()

Solution

  • Skip invalid lines with try/except:

      ...
      s = ser.readline().decode()
      if s != "":
        try:
          rows = [float(x) for x in s.split(',')]
          rows.insert(0, int(time()))
          print(rows)
          writer.writerow(rows)
          f.flush()
        except ValueError:
          print('Invalid line')
      ...
    

    or this way (no need to try):

    rows = [float(x) for x in list(filter(lambda x: x.isdigit(), a.split(',')))]