我正在尝试从多个设备收集串行数据,时间戳,并将其导出到.csv文件。我想为每个设备编写单独的模块,以便它们将数据返回到主模块,并在其中完成对csv的所有写入。
以下程序将日期和时间写入csv,但不写入从设备模块返回的数据。
import time
import csv
from threading import Thread
import fio2
def Csv_creator():
my_file = open('test_csv.csv', 'w+')
with my_file:
new_file = csv.writer(my_file)
def Timestamp():
date_now = time.strftime('%d/%m/%y')
time_now = time.strftime('%H:%M:%S')
return [date_now,time_now]
def Write_loop():
Csv_creator()
fio2.Initialize()
while True:
with open('test_csv.csv', 'a') as f:
[date_now,time_now] = Timestamp()
fio2_data = fio2.Reader()
print fio2_data
to_write = [date_now,time_now,fio2_data]
csv_file = csv.writer(f)
csv_file.writerow(to_write)
t = Thread(target=Write_loop)
t.daemon = True
t.start()
raw_input("Press any key to stop \n")设备模块如下图所示。它自己可以很好地工作,但我很难让它返回值并将其写入csv文件。
import serial
ser = serial.Serial("COM6",
baudrate=2400,
bytesize=serial.EIGHTBITS,
parity =serial.PARITY_ODD,
timeout=1,
writeTimeout =1)
def Initialize():
global ser
try:
ser.isOpen()
print("\n Serial is open")
except:
print ("Error: serial Not Open")
def Reader():
global ser
if (ser.isOpen()):
try:
x = ser.readline().decode()
x = (x)
return x
except:
return "unable to print"
else:
return "cannot open serial port"发布于 2018-03-06 08:35:58
我想通了。我不得不删除一些与十进制值相关的垃圾字母。首先,我将接收到的数据更改为字符串,并替换垃圾字母。下面是我是如何改变它的:
[date_now,time_now] = Timestamp()
fio2_data = str(fio2.Reader()).replace("\r\n","")
fio2_data = fio2_data.replace("\x000","")
write_list = [date_now,time_now,fio2_data]发布于 2018-03-05 02:59:56
我建议将文件移到外部,而不是每次都在循环中打开文件:
with open('test_csv.csv', 'a') as f:
csv_file = csv.writer(f)
while True:
date_now, time_now = Timestamp()
fio2_data = fio2.Reader()
csv_file.writerow([date_now, time_now, fio2_data])https://stackoverflow.com/questions/49080298
复制相似问题