You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将PySerial采集的串口数据(含时间戳)导出至CSV?及写入异常解决

Hey there! Let's troubleshoot why your device's serial data isn't making it into your CSV file—even though you can print it just fine. Here are the most common fixes and debugging steps to get this sorted:

1. Fix Serial Data Reading Logic

Chances are, you're not properly capturing the full data stream from your device. Serial data often comes in chunks or is delimited by newlines, so using readline() instead of raw read() ensures you grab complete records. Don't forget to decode and clean the data too!

Example code snippet:

import serial
import csv
from datetime import datetime

# Replace with your serial port parameters
ser = serial.Serial('COM3', 9600, timeout=1)

with open('serial_data.csv', 'a', newline='') as csv_file:
    csv_writer = csv.writer(csv_file)
    
    # Write header if file is empty
    csv_file.seek(0, 2)
    if csv_file.tell() == 0:
        csv_writer.writerow(['Timestamp', 'Device Data'])
    
    while True:
        # Read full line, decode, and strip extra whitespace/newlines
        raw_data = ser.readline().decode('utf-8').strip()
        if raw_data:  # Only process non-empty data
            timestamp = datetime.now().strftime('%Y-%m-%d %H:%M:%S.%f')[:-3]  # Millisecond precision
            print(f"Received: {raw_data}")  # Confirm data is captured
            csv_writer.writerow([timestamp, raw_data])
            csv_file.flush()  # Force write to disk immediately (avoids cache delays)
2. Validate CSV File Handling

Double-check how you're opening and writing to the CSV file:

  • Use 'a' (append) mode instead of 'w' (write) to avoid overwriting existing data.
  • Always include newline='' when opening the file—this prevents extra blank lines in your CSV (a common gotcha with the csv module).
  • Call flush() after each write to ensure data isn't stuck in memory instead of being saved to disk.
3. Check for Encoding Mismatches

Your device might not be sending UTF-8 encoded data. If decoding fails, you'll end up with empty or garbled strings. Try using ASCII encoding (common for serial devices) with error handling:

raw_data = ser.readline().decode('ascii', errors='replace').strip()

The errors='replace' flag will swap unreadable characters with � instead of crashing your program.

4. Isolate the Problem with a Test

To rule out CSV writing issues entirely, test with mock data:

import csv
from datetime import datetime

with open('test.csv', 'a', newline='') as test_file:
    writer = csv.writer(test_file)
    writer.writerow(['Timestamp', 'Mock Data'])
    mock_device_data = "Temperature: 25.5°C, Humidity: 60%"
    timestamp = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
    writer.writerow([timestamp, mock_device_data])

If this works, the problem is definitely in how you're reading from the serial port—go back to step 1 to verify baud rate, parity, stop bits, and timeout settings match your device's specs.

内容的提问来源于stack exchange,提问作者Shawn

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 07:19:58