首页 > 解决方案 > ValueError:无法将字符串转换为浮点数:'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()

标签: python-3.9

解决方案


跳过无效行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(',')))]

推荐阅读