Home / Learn / Code for makers

Read and write CSV files in Python (with sensor log examples)

Python's csv module writing rows of time, temperature and humidity to log.csv, shown open as a spreadsheet with the same columns
Beginner

CSV (comma-separated values) is the simplest way to save data from a project, such as sensor readings, so you can open it in Excel or Google Sheets later. Python's built-in csv module handles all the awkward cases for you. Every example below was run on Python 3.13 and the output is copied from the run.

Write a CSV file

import csv

rows = [
    ["time", "temp_c", "humidity"],
    ["09:00", 19.5, 52],
    ["09:10", 20.1, 50],
    ["09:20", 20.8, 49],
]
with open("log.csv", "w", newline="", encoding="utf-8") as f:
    writer = csv.writer(f)
    writer.writerows(rows)

Always open CSV files with newline="". The csv module writes its own line endings, and without it you get a blank line between every row on Windows. with closes the file for you, even if something goes wrong.

Read it back

with open("log.csv", newline="", encoding="utf-8") as f:
    for row in csv.reader(f):
        print(row)
['time', 'temp_c', 'humidity']
['09:00', '19.5', '52']
['09:10', '20.1', '50']
['09:20', '20.8', '49']

Every value comes back as a string: CSV files don't store types. Convert with float() or int() before doing maths.

Use column names with DictReader

import csv

with open("log.csv", newline="", encoding="utf-8") as f:
    reader = csv.DictReader(f)
    temps = []
    for row in reader:
        temps.append(float(row["temp_c"]))
        print(row["time"], row["temp_c"])

print(f"Average: {sum(temps) / len(temps):.2f} °C")
09:00 19.5
09:10 20.1
09:20 20.8
Average: 20.13 °C

DictReader uses the first row as the column names, so each row is a dictionary. Your code keeps working if someone adds or reorders columns.

Add a row to an existing file

import csv

new = {"time": "09:30", "temp_c": 21.2, "humidity": 48}
with open("log.csv", "a", newline="", encoding="utf-8") as f:
    writer = csv.DictWriter(f, fieldnames=["time", "temp_c", "humidity"])
    writer.writerow(new)
time,temp_c,humidity
09:00,19.5,52
09:10,20.1,50
09:20,20.8,49
09:30,21.2,48

Mode "a" appends, which is what you want for a data logger: each new reading goes on the end and nothing is lost if the program restarts. For a new file, call writer.writeheader() once first to write the column names.

Commas and quotes inside values

import csv, io
text = 'part,note\nLED,"red, 5 mm"\nresistor,"say ""hi"""\n'
for row in csv.reader(io.StringIO(text)):
    print(row)
print("LED,red, 5 mm".split(","))
['part', 'note']
['LED', 'red, 5 mm']
['resistor', 'say "hi"']
['LED', 'red', ' 5 mm']

A value containing a comma is wrapped in quotes, and a quote inside a value is doubled. The csv module reads and writes these correctly. Splitting each line on commas yourself, as in the last line, breaks as soon as a value contains one.

Files from Excel

import csv
with open("excel.csv", "w", newline="", encoding="utf-8-sig") as f:
    csv.writer(f).writerow(["temp_c", "note"])
with open("excel.csv", "rb") as f:
    print(f.read()[:3])
with open("excel.csv", newline="", encoding="utf-8") as f:
    print(next(csv.reader(f)))
with open("excel.csv", newline="", encoding="utf-8-sig") as f:
    print(next(csv.reader(f)))
b'\xef\xbb\xbf'
['\ufefftemp_c', 'note']
['temp_c', 'note']

Excel's "CSV UTF-8" format starts the file with three hidden bytes, a byte order mark. Read it with plain utf-8 and your first column name gets a stray \ufeff on the front, so row["temp_c"] gives a KeyError. Open such files with encoding="utf-8-sig", which removes it. Writing with utf-8-sig also helps Excel show symbols like ° and Ω correctly.

Tips for data loggers

  • Write the time in a sortable format such as 2026-11-21 09:00:00; see Python f-strings for formatting dates.
  • Store numbers without units in the values and put the unit in the column name, like temp_c, so spreadsheets treat them as numbers.
  • For big data sets or analysis, the pandas library's read_csv is worth learning, but the built-in module is all a logger needs.

For a complete logger, see the Pico temperature logger project.

Sources

The main references behind this guide. Numbers we worked out ourselves, such as the code outputs, come from running the code.