python-3.9 - 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()
解决方案
跳过无效行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(',')))]
推荐阅读
- flow - PowerApps:无法为 SSL/TLS 安全通道建立信任关系
- r - 在保留行数的同时解包多行小标题的列表列
- twilio - 我可以将可编程视频与语音通话结合起来吗?
- c - C 中的 const char * const VS const char []
- oracle - 如何在 SSRS 2014 上设置 Oracle 数据源
- javascript - for await 循环在遍历 Mongoose QueryCursor 时丢失元素
- javascript - 我的 if else 语句有问题,没有从 javascript 中的 if 返回
- javascript - 在 Javascript localStorage 中存储密码
- html - 如何在css中一个接一个地添加脉冲动画,比如红绿灯不断闪烁
- angular - 无法设置标头,因为拦截器在将令牌存储在本地存储 Angular 8 TypeScript 之前拦截请求