这里有一些简单的代码。数据不会累积在CSV文件中; 有人可以共享代码从串口读取数据并将其记录到CSV文件吗?
import serial
import csv
import string
import os
import time
import sys
def main():
pass
if __name__ == '__main__':
main()
count=0
f=open("test.txt","w+");
result = csv.writer(f,delimiter=',', dialect='excel-tab')
result_statememt=("date","zenith","elevation","azimuth","conv_elevation");
result.writerow(result_statememt)
f.close()
while(count<10):
#time.sleep(60)
ser=serial.Serial()
ser.port=3
ser.baudrate=9600
ser.open()
str=ser.read(50)
val=str.split(":")
lines=str.split("\r\n")
count=count+1
print count
f=open("test.txt","a+")
result=csv.writer(f,delimiter=',')
result.writerow()
f.close()
f.close()
ser.close()
答案 0 :(得分:2)
如上所述,由于您未向result.writerow()
传递任何内容,因此不会向CSV文件写入任何内容。但是我也担心你一次从串口读取50个字节,然后将其拆分为:
字符,然后将其拆分为\r\n
分隔符。我不认为这会做你想做的事。
我的猜测是,您希望串行端口提供由\r\n
终止的行,每行包含一组由:
分隔的字段,并且您希望将这些字段写入CSV文件。我建议尝试这样的事情:
with open("test.txt", "wb") as output_file:
csv_out = csv.writer(output_file, delimiter=',', dialect='excel-tab')
csv_out.writerow("date","zenith","elevation","azimuth","conv_elevation")
ser=serial.Serial(port=3, baudrate=9600, timeout=60)
ser.open()
for count in range(10):
str = ser.readline().rstrip()
csv_out.writerow(str.split(':'))
ser.close()
我还没有使用过Python serial
模块,而且目前还没有硬件来测试这个模块,但根据我对模块文档的阅读,这应该更接近您想要做的事情。我认为读取超时是以秒为单位测量的,因此如果串口在一分钟内没有产生任何数据,这将超时。
答案 1 :(得分:0)
import serial
import csv
import string
import os
import time
import sys
def main():
pass
if __name__ == '__main__':
main()
ser=serial.Serial()
ser.port=2
print ser.port
ser.baudrate=9600
with open("test.csv", "wb") as output_file:
csv_out = csv.writer(output_file, delimiter=',', dialect='excel-tab')
C_statememt=("date","time","Zenith","Azimuth","Elevation","conv_elevation");
ser.open()
for count in range(10):
str = ser.readline().rstrip()
C_statememt.writerow(str.split(':'))
ser.close()
错误报告:
2
Traceback (most recent call last):
File "C:\Documents and Settings\Administrator\My Documents\python code\code3\module1.py", line 28, in <module>
C_statememt.writerow(str.split(':'))
AttributeError: 'tuple' object has no attribute 'writerow'