首页 > 解决方案 > 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_sensortimestamp column 如下所示:

我可以检查这是否是 Unicode 问题(需要不同的语法来合并字符串)?正如打印行所指示的那样。

标签: pythoncsvpython-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

推荐阅读