对unicode进行btye修改并保存为csv

gjmwrych  于 2021-08-25  发布在  Java
关注(0)|答案(1)|浏览(393)

我可以成功地接收长字符串中的串行数据,例如 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问题(需要不同的语法来合并字符串)?如打印行所示。

pn9klfpd

pn9klfpd1#

每次循环打开/附加和关闭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

相关问题