如何将使用PySerial收集的串行数据导出到csv文件?

时间:2018-03-05 20:26:45

标签: python csv serial-port timestamp pyserial

我正在尝试从设备收集串行数据,时间戳并将其导出到.csv文件。

以下程序将日期和时间写入csv,但不写入从设备模块返回的数据:

import time
import csv
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()

    with open('test_csv.csv', 'a') as f:
            csv_file = csv.writer(f)

            for num in range(0,20):

                [date_now,time_now] = Timestamp()
                fio2_data = fio2.Reader()
                print(fio2_data)
                csv_file.writerow([date_now,time_now,fio2_data])   

    Write_loop()

设备模块如下所示。它返回数据,我可以打印它。唯一的问题是无法将其写入csv文件。

import serial

ser = serial.Serial("COM4",
                    baudrate=2400,
                    bytesize=serial.EIGHTBITS,
                    parity =serial.PARITY_ODD)


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"

1 个答案:

答案 0 :(得分: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]