python: 从arduino串口转成csv文件,为什么数据格式奇怪?
python: from arduino serial port to csv file, why the data format is strange?
/抱歉我的英文水平有限,可能导致问题不是很清楚。/
我现在正在使用 python 将从 arduino 发送的数据写入 csv 文件,我想要一组大约 200 个数据,一行一组,每个数据分别在不同的列中。来自我的aruino的数据格式为:数字+,(例如:123,144,135,....)但是在csv文件中,数字被分成不同的列(1,2,3在不同的列中而不是123在一个列中colum), 写note打开文件时,数据看起来像"1,2,3","1,4,4",.....
我尝试了不同的分隔符,例如 \t、space... 当我通过 excel 查看文件时 \t 看起来不错,但在书写板(每个之间的制表符)中仍然不起作用两个数字)。
我还尝试删除 arduino 代码中的“,”,但它也无济于事。
在 writerows() 函数中,我尝试了数据, str(data) 和 str(data)+"," ,没有太大区别。
我什至将笔记本电脑的分隔符设置从“,”更改为“\t”,但没有用。
arduino部分:
Serial.print(value);
Serial.print(",");
python部分:
while True:
try:
ser_bytes = ser.readline()
decoded_bytes = ser_bytes.decode('utf-8')
print(decoded_bytes)
#decoded_bytes = decoded_bytes.strip('|')
with open("test_data.csv","a",newline="") as f:
writer = csv.writer(f,delimiter=",")
writer.writerows([str(decoded_bytes),])
我搜索了很多关于 csv 格式的信息,但我仍然不明白为什么代码不起作用。
谢谢你的帮助。
你说得对,我想我没有完全明白你的问题是什么,但这里有一些想法。要获得正确的 csv 输出,您必须将代码更改为如下内容:
while True:
try:
ser_bytes = ser.readline()
// the following line splits the line you got from your arduino into an array
decoded_bytes = ser_bytes.split(",");
print(decoded_bytes)
with open("test_data.csv","a") as f:
writer = csv.writer(f,delimiter=",")
writer.writerow(decoded_bytes)
像这样你应该得到正确的 csv 输出,你从 arduino 得到的每一行都被写入文件中的一行。
一些额外的想法:由于您已经从 arduino 获得了 csv 样式的行,因此您可以直接将其写入文件,而无需拆分和使用 csv 编写器。这实际上有点矫枉过正,但可能无关紧要;)
/抱歉我的英文水平有限,可能导致问题不是很清楚。/ 我现在正在使用 python 将从 arduino 发送的数据写入 csv 文件,我想要一组大约 200 个数据,一行一组,每个数据分别在不同的列中。来自我的aruino的数据格式为:数字+,(例如:123,144,135,....)但是在csv文件中,数字被分成不同的列(1,2,3在不同的列中而不是123在一个列中colum), 写note打开文件时,数据看起来像"1,2,3","1,4,4",.....
我尝试了不同的分隔符,例如 \t、space... 当我通过 excel 查看文件时 \t 看起来不错,但在书写板(每个之间的制表符)中仍然不起作用两个数字)。 我还尝试删除 arduino 代码中的“,”,但它也无济于事。 在 writerows() 函数中,我尝试了数据, str(data) 和 str(data)+"," ,没有太大区别。 我什至将笔记本电脑的分隔符设置从“,”更改为“\t”,但没有用。
arduino部分:
Serial.print(value);
Serial.print(",");
python部分:
while True:
try:
ser_bytes = ser.readline()
decoded_bytes = ser_bytes.decode('utf-8')
print(decoded_bytes)
#decoded_bytes = decoded_bytes.strip('|')
with open("test_data.csv","a",newline="") as f:
writer = csv.writer(f,delimiter=",")
writer.writerows([str(decoded_bytes),])
我搜索了很多关于 csv 格式的信息,但我仍然不明白为什么代码不起作用。 谢谢你的帮助。
你说得对,我想我没有完全明白你的问题是什么,但这里有一些想法。要获得正确的 csv 输出,您必须将代码更改为如下内容:
while True:
try:
ser_bytes = ser.readline()
// the following line splits the line you got from your arduino into an array
decoded_bytes = ser_bytes.split(",");
print(decoded_bytes)
with open("test_data.csv","a") as f:
writer = csv.writer(f,delimiter=",")
writer.writerow(decoded_bytes)
像这样你应该得到正确的 csv 输出,你从 arduino 得到的每一行都被写入文件中的一行。
一些额外的想法:由于您已经从 arduino 获得了 csv 样式的行,因此您可以直接将其写入文件,而无需拆分和使用 csv 编写器。这实际上有点矫枉过正,但可能无关紧要;)