【发布时间】:2021-09-18 19:56:24
【问题描述】:
我可以成功接收长字符串中的串行数据,例如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 问题(需要不同的语法来合并字符串)?正如打印行所指示的那样。
【问题讨论】:
标签: python csv python-unicode