如何为使用PySerial收集的数据加时间戳并导出到csv?

问题描述 投票:0回答:2

我正在尝试从多个设备收集串行数据,时间戳并将其导出到.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"
python multithreading csv timestamp pyserial
2个回答
0
投票

我不建议每次在循环中打开文件,而是建议将其移到外面:

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])

0
投票

我想到了。我不得不删除一些与小数值相关的垃圾信件。首先,我将收到的数据更改为字符串并替换垃圾字母。这是我改变它的方式:

[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]
© www.soinside.com 2019 - 2024. All rights reserved.