如何将逗号分隔的对象导出到 .csv 文件

How to export comma separated object into a .csv file

下面的代码是将指定串口的原始数据输出到python shell以及修改后的CSV格式的数据,准备通过[=32=输出] 到 .csv 文件中。但是,最终输出显示为 Fri Apr 23 21:30:05 2021 "19,62,0,0,25。您可能会发现这是不正确的,因为输出应为 [time.asctime(time.localtime(time.time())),decoded_bytes] 翻译成 Fri Apr 23 21:30:05 2021, 19,62,0,0,25。我不确定添加了 ' " ',也没有说明 python 考虑日期时间对象的 '19' 部分并将其放在同一列中的原因。任何帮助将不胜感激。

import serial
import time
import csv

#ser = serial.Serial('/dev/ttyUSB0', baudrate = 9600, timeout = 1)
ser = serial.Serial('COM4', baudrate = 9600)
ser.flushInput()

while True:
    
    ser_bytes = ser.readline()
    line = ser.readline().decode('utf-8')[:-1]
    decoded_bytes = line.replace(":","",5).replace("Soil Moisture","",1).replace("Humidity","",1).replace("CO2","",1).replace("ppm","",1).replace("ppb","",1).replace("%RH","",1).replace("Temp","",1).replace("EC","",1).replace("TVOC","",1).replace(" ","",8)

    if line:  # If it isn't a blank line
        print("Incoming DATA:")
        print(line)
        print(".csv DATA:")
        print(decoded_bytes)
        with open("test_data.csv","a") as f:
            writer = csv.writer(f,delimiter=" ")
            writer.writerow([time.asctime(time.localtime(time.time())),decoded_bytes])

样本pythonshell输出:

传入数据: 土壤水分:22EC,湿度:62.00%RH,CO2:0ppm,TVOC:0ppb,Temp:25.00

.csv 数据: 22,62.00,0,0,25.00

传入数据: 土壤水分:18EC,湿度:62.00%RH,CO2:400ppm,TVOC:0ppb,Temp:24.45

.csv 数据: 18,62.00,400,0,24.45

传入数据: 土壤水分:15EC,湿度:62.00%RH,CO2:400ppm,TVOC:0ppb,Temp:25.00

.csv 数据: 15,62.00,400,0,25.00

尝试调整此解决方案,看看是否有帮助。

file_input.txt

Soil Moisture: 22EC, Humidity: 62.00%RH, CO2: 0ppm, TVOC: 0ppb, Temp:25.00
Soil Moisture: 18EC, Humidity: 62.00%RH, CO2: 400ppm, TVOC: 0ppb, Temp:24.45
Soil Moisture: 15EC, Humidity: 62.00%RH, CO2: 400ppm, TVOC: 0ppb, Temp:25.00

script

import time



import re

def write_to_csv(list_input):
    import csv
    with open('file_output.csv', 'a', newline='') as myfile:
        wr = csv.writer(myfile, quoting=csv.QUOTE_NONNUMERIC)
        wr.writerow(list_input)

def read_input(file_input):
    with open(file_input, 'r') as file_in:
        list_file = file_in.read().splitlines()
        for i in list_file:
            # Find the pattern
            res=re.findall(': ?(\d*\.?\d*)', i)
            # Convert the list to number
            res=list(map(float,res))
            time_stamp = time.asctime(time.localtime(time.time()))
            res.insert(0,time_stamp)
            write_to_csv(res)


file_input = 'file_input.txt'
read_input(file_input)

file_output.csv

"Fri Apr 23 10:29:11 2021",22.0,62.0,0.0,0.0,25.0
"Fri Apr 23 10:29:11 2021",18.0,62.0,400.0,0.0,24.45
"Fri Apr 23 10:29:11 2021",15.0,62.0,400.0,0.0,25.0