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

2024-04-27 02:25:56 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试从多个设备收集串行数据,时间戳并将其导出到.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文件。在

^{pr2}$

Tags: 模块文件csvto数据importdatadate
2条回答

与其每次在循环中打开文件,我建议将其移到外部:

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

我想出来了。我不得不删除一些与十进制值相关的垃圾字母。首先,我将接收到的数据更改为字符串并替换垃圾字母。我是怎么改的:

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

相关问题 更多 >