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

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

我想 运行 我的代码使用 Arduino 和 Python。我必须编写一个脚本来串行获取数据并将其保存到 CSV 文件中。当我 运行 脚本时出现此错误 "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()

跳过无效行 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')
  ...

或者这样(不需要try):

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