python - Btye 到 Unicode 修改并保存到 CSV
问题描述
我可以成功接收长字符串中的串行数据,例如332,10.00,87.00
,,
分隔符将帮助随后将不同的连接值排序到 CSV 中的相应行中。
但是,我想332,10.00,87.00,35.00
通过将接收到的串行数据与另一个字符串变量连接来修改串行字符串数据,如下所示:
#serial communication
ser = serial.Serial('COM8',9600)
ser.flushInput()
field_names = ['Time Stamp','Sensor 1','Sensor 2','New Sensor']
force_filename_perm = 'Sensor_Data.csv'
def forcerecording():
global field_names, new_sensor, FIRST_TIMELOOP, force_filename_perm
if FIRST_TIMELOOP:
with open(force_filename_perm,"a") as f:
writer = csv.writer(f,delimiter=",")
writer.writerow(field_names)
f.close()
try:
ser_bytes = ser.readline()
decoded_bytes = ser_bytes.decode("utf-8")
final_bytes = decoded_bytes + "," + str(new_sensor)
print("Final Decode:", final_bytes)
f = open(force_filename_perm,"a")
f.write(final_bytes)
f.close()
except:
print("Keyboard Interrupt")
while(1):
forcerecording()
#Some Operations done to obtain float `new_sensor` value
但是,该new_sensor
值也将转移到打印行中的新行,即
Final Decode: 332,10.00,87.00
,35.00
代替:
Final Decode: 332,10.00,87.00,35.00
此外,在 CSV 文件中new_sensor
,timestamp column
我可以检查这是否是 Unicode 问题(需要不同的语法来合并字符串)?正如打印行所指示的那样。
解决方案
每个循环打开/附加和关闭 CSV 文件会非常慢,如果保持文件打开会更快。
您还可以混合使用 CSV 库并尝试自己创建字段,我建议您坚持使用csv.writer()
. 由于串行数据似乎有逗号,您可以将其拆分并创建一个列表,该列表可以与您的新传感器值组合。
例如:
#serial communication
ser = serial.Serial('COM8',9600)
ser.flushInput()
field_names = ['Time Stamp', 'Sensor 1', 'Sensor 2', 'New Sensor']
force_filename_perm = 'Sensor_Data.csv'
def forcerecording(csv_output):
global field_names, new_sensor, FIRST_TIMELOOP, force_filename_perm
try:
ser_bytes = ser.readline()
decoded_bytes = ser_bytes.decode("utf-8")
# Remove trailing newline from decoded_bytes and split the values
row = [*decoded_bytes.strip().split(','), new_sensor]
print("Final Decode:", row)
csv_output.writerow(row)
except:
print("Keyboard Interrupt")
with open(force_filename_perm, 'w', newline='') as f_output:
csv_output = csv.writer(f_output)
csv_output.writerow(field_names)
while True:
forcerecording(csv_output)
#Some Operations done to obtain float `new_sensor` value
推荐阅读
- swiftui - 如何修复在 Swift 中找不到文件 json
- python - 用 pandas 加载 csv 的问题
- rust - 更改闭包内的向量会导致“借用移动值”错误
- java - org.apache.kafka.common.errors.TimeoutException:获取主题元数据时超时
- apache-kafka - SerializationException:反序列化 Avro 消息时出错
- c# - NetCore 2.2 中的版本控制
- ruby-on-rails - How to decrypt signed cookies
- file - 为什么我的缓存在 Laravel 4.2 上使用 0 分钟时不会过期
- c# - 在 Visual Studio 代码分析器 (Roslyn) 中确定目标框架
- angular - 如何在 Jhipster (spring boot + angular) 应用程序上设置上下文路径