Logging to CSV files helps you save data in a simple table format. This makes it easy to read, share, and analyze later.
0
0
Logging to CSV files in Raspberry Pi
Introduction
You want to record sensor data like temperature or humidity over time.
You need to keep track of events or errors from your Raspberry Pi projects.
You want to export data for use in spreadsheet programs like Excel.
You want a simple way to log data without complex databases.
Syntax
Raspberry Pi
import csv with open('filename.csv', mode='a', newline='') as file: writer = csv.writer(file) writer.writerow([data1, data2, data3])
Use mode='a' to add data without erasing old logs.
newline='' prevents blank lines between rows on some systems.
Examples
This adds a header row to the CSV file.
Raspberry Pi
import csv with open('log.csv', 'a', newline='') as file: writer = csv.writer(file) writer.writerow(['Time', 'Temperature', 'Humidity'])
This adds a data row with time, temperature, and humidity values.
Raspberry Pi
import csv with open('log.csv', 'a', newline='') as file: writer = csv.writer(file) writer.writerow(['12:00', 22.5, 60])
Sample Program
This program logs the current time, a random temperature, and humidity to a CSV file named 'sensor_log.csv'. It adds a header if the file is empty or does not exist.
Raspberry Pi
import csv from datetime import datetime import random import os filename = 'sensor_log.csv' # Check if file exists and is empty file_exists = os.path.isfile(filename) with open(filename, 'a', newline='') as file: writer = csv.writer(file) if not file_exists or os.path.getsize(filename) == 0: writer.writerow(['Timestamp', 'Temperature', 'Humidity']) timestamp = datetime.now().strftime('%Y-%m-%d %H:%M:%S') temperature = round(random.uniform(20.0, 25.0), 2) humidity = random.randint(40, 70) writer.writerow([timestamp, temperature, humidity]) print(f"Logged data: {timestamp}, {temperature}°C, {humidity}%")
OutputSuccess
Important Notes
Always open the file with newline='' to avoid extra blank lines in Windows.
Use 'a' mode to keep old logs and add new data.
Check if the file is empty before writing headers to avoid duplicates.
Summary
Logging to CSV files stores data in a simple, readable table format.
Use Python's csv module to write rows easily.
Open files in append mode to keep adding data without erasing old logs.