如何将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:
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)
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 thecsvmodule). - Call
flush()after each write to ensure data isn't stuck in memory instead of being saved to disk.
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.
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

