Skip to content
Tactiverge

Reading files and CSV data

Save and load data with Python's standard library: write and read text files safely, parse CSV logs with the csv module, cope with missing values and save your results.

Lesson 5 of 6 · 35 min · Self-paced · Free

Why files?

Everything so far has lived inside the program: you typed the readings into a list. Real data does not arrive that way. A data logger writes a file to a memory card; a robot saves a log of every run; a teammate emails a spreadsheet of test results. To analyse any of it, your program must read files — and to share your results, it must write them.

The most common format for engineering data is CSV, "comma-separated values": a plain text file where each line is a row and commas separate the columns. Spreadsheets can open and save it, and Python can read it with nothing but its standard library.

To follow along, run each example from the same folder. The first example creates the file that the next ones read, so you do not need any data of your own.

Writing a text file

lines = ["time_s,temp_c", "0,21.4", "10,21.9", "20,22.7", "30,23.1"]

with open("temps.csv", "w", encoding="utf-8") as f:
    for line in lines:
        f.write(line + "\n")

print("Saved temps.csv")

Output:

Saved temps.csv

open(name, "w") opens a file for writing, creating it — or replacing it, without warning, if it already exists. The with statement closes the file automatically when the indented block ends, even if something goes wrong part-way through. Always use it. \n is the newline character; write does not add one for you. encoding="utf-8" makes sure symbols such as °C are saved the same way on every computer.

Reading it back

Opening a file with no mode reads it. Looping over the file gives one line at a time:

with open("temps.csv", encoding="utf-8") as f:
    for line in f:
        print(repr(line))

Output:

'time_s,temp_c\n'
'0,21.4\n'
'10,21.9\n'
'20,22.7\n'
'30,23.1\n'

repr shows exactly what is in each string, including the invisible newline at the end. Every line is text, even the ones that look like numbers. To use the data, strip off the newline, split at the comma and convert:

times = []
temps = []

with open("temps.csv", encoding="utf-8") as f:
    header = f.readline()          # read and skip the first line
    for line in f:
        t_text, temp_text = line.strip().split(",")
        times.append(float(t_text))
        temps.append(float(temp_text))

print(times)
print(temps)
rate = (temps[-1] - temps[0]) / (times[-1] - times[0])   # °C per second
print(f"Warming at {rate * 60:.2f} °C per minute")

Output:

[0.0, 10.0, 20.0, 30.0]
[21.4, 21.9, 22.7, 23.1]
Warming at 3.40 °C per minute

.strip() removes spaces and newlines from both ends, and .split(",") breaks the line into a list of pieces. Forgetting to convert is a classic bug: "21.4" < "3.0" is True, because strings are compared letter by letter, not by value.

When splitting by commas breaks

Splitting on commas works until a field itself contains a comma — for example a note such as "load added, then removed". CSV handles this by putting such fields in quotes, and the standard csv module understands the rules. Let us create a made-up log from a small drive test using csv.writer:

import csv

rows = [
    ["time_s", "current_a", "rpm", "note"],
    [0.0, 0.42, 0, "start"],
    [0.5, 1.85, 140, ""],
    [1.0, 1.10, 210, ""],
    [1.5, "", 212, "current sensor dropout"],
    [2.0, 1.04, 215, "load added, then removed"],
]

with open("drive_log.csv", "w", newline="", encoding="utf-8") as f:
    csv.writer(f).writerows(rows)

with open("drive_log.csv", encoding="utf-8") as f:
    print(f.read())

Output:

time_s,current_a,rpm,note
0.0,0.42,0,start
0.5,1.85,140,
1.0,1.1,210,
1.5,,212,current sensor dropout
2.0,1.04,215,"load added, then removed"

The writer added quotes around the note containing a comma, and left an empty field where a current reading is missing. The newline="" argument is what the csv documentation asks for when opening files for the csv module; it stops blank lines appearing between rows on some systems.

Reading CSV with DictReader

csv.DictReader reads the header row for you and returns each following row as a dictionary, keyed by column name. That makes code readable and robust to someone adding a column later:

import csv

currents = []
missing = 0

with open("drive_log.csv", newline="", encoding="utf-8") as f:
    for row in csv.DictReader(f):
        if row["current_a"] == "":
            missing += 1
            continue                  # skip to the next row
        currents.append(float(row["current_a"]))

print(f"{len(currents)} current readings, {missing} missing")
print(f"Peak current: {max(currents):.2f} A")
print(f"Mean current: {sum(currents) / len(currents):.3f} A")

Output:

4 current readings, 1 missing
Peak current: 1.85 A
Mean current: 1.103 A

Every value from DictReader is a string, so we still convert with float. continue jumps straight to the next row of the loop. Note that we counted the missing value instead of silently dropping it: "mean of 4 readings, 1 missing" is an honest summary; "mean current 1.103 A" on its own hides a gap in the data.

Writing your results

Results are worth saving too, so a report or another program can use them. Here we compute a summary for each column and write it to a new file, leaving the original log untouched:

import csv

with open("drive_log.csv", newline="", encoding="utf-8") as f:
    rows = list(csv.DictReader(f))

summary = []
for column in ["current_a", "rpm"]:
    values = [float(r[column]) for r in rows if r[column] != ""]
    summary.append([column, len(values), min(values), max(values)])

with open("drive_summary.csv", "w", newline="", encoding="utf-8") as f:
    writer = csv.writer(f)
    writer.writerow(["column", "count", "min", "max"])
    writer.writerows(summary)

with open("drive_summary.csv", encoding="utf-8") as f:
    print(f.read(), end="")

Output:

column,count,min,max
current_a,4,0.42,1.85
rpm,5,0.0,215.0

list(csv.DictReader(f)) reads every row into a list of dictionaries — the "table" structure from the lesson on lists and dictionaries. That is fine for files of thousands of rows. For very large logs, loop over the reader row by row as in the previous example, so the whole file never has to fit in memory at once.

When the file is not where you think

If Python cannot find a file, it stops with FileNotFoundError. A relative name like "drive_log.csv" is looked up in the current working directory — usually the folder you ran the program from, which is not always the folder containing your script. import os followed by print(os.getcwd()) shows where Python is looking. Keeping data files next to your script, and running the script from that folder, avoids most of these problems.

Knowledge check

Check your understanding

  1. 1. What happens if you run open("results.csv", "w") and results.csv already exists?
  2. 2. Each line read from a text file such as temps.csv is…
  3. 3. Why use the csv module rather than line.split(",")?
  4. 4. A log has 50 rows and 3 have an empty temperature field. What is the most honest summary?
  5. 5. Your program raises FileNotFoundError for "log.csv", but the file is definitely on your computer. What is the most likely cause?

Project

Programming project: a log processor

Write a program in two parts.

Part 1 — make the data. Write a CSV file called room_log.csv with columns time_s, temp_c and humidity_pct and at least 30 rows of made-up readings, one every 10 seconds. Put a comment saying the data is made up. Leave at least two fields empty and put the text ERR in one.

Part 2 — analyse it. Using csv.DictReader:

  1. For each of the two measurement columns, count the valid, empty and non-numeric values. (Hint: a value is numeric if it is not empty and not ERR; the lesson on errors shows a more general method.)
  2. Compute the minimum, maximum and mean of each column using only valid values.
  3. Write the results to room_summary.csv, one row per column, and print the summary file.
  4. Confirm that room_log.csv is unchanged by printing its first three lines at the end.

No hardware is required.

Deliverables

  • A Python 3 program that writes room_log.csv and produces room_summary.csv
  • Printed output showing counts of valid and missing values for each column
  • The contents of room_summary.csv

Go further

Reading files and CSV data — Computational Engineering — Tactiverge