字节到 Unicode 修改并保存到 CSV

Btye to Unicode modification and saving into 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