---
title: Text and CSV data
heading: Getting measurements out of files
eyebrow: A4 · Lesson 47 · Text and CSV data
xp: 40
---

::: hook
Oscilloscopes, data loggers, spreadsheets and simulators all export the same thing: a text file of comma-separated values, with a header line naming the columns, maybe some comment lines, and the occasional blank or broken entry. Before any analysis, you have to read that file into arrays without losing or misreading a value. Python's `csv` module and NumPy's loaders do it in a line or two, once you know which to use.
:::

::: predict
## A CSV file's first line is `t,v,i` and the rest are numbers. What does `np.loadtxt(f, delimiter=",")` do with it?

- [ ] Reads the header as column names
- [x] Fails, because `t` can't be read as a number
- [ ] Skips the header automatically
- [ ] Reads everything as text

::: reveal
It fails with a `ValueError`. `loadtxt` expects numbers on every line it reads, so you have to tell it to skip the header with `skiprows=1`. `np.genfromtxt(..., names=True)` reads the header as names instead.
:::
:::

::: nameit
## CSV text

A CSV ("comma-separated values") file is plain text:

```
# logged 2026-11-18, channel A
t,v,i
0.000,0.00,1.000
0.001,0.95,0.905
0.002,1.81,0.819
```

In these browser labs the "file" is a string, wrapped by `io.StringIO` so it behaves like an open file. On your own machine you'd use `open("data.csv")` in its place.

## Three ways to read it

**`csv.DictReader`**: each row becomes a dictionary keyed by the header names. Flexible, and good for mixed text and numbers.

```
import csv, io
rows = list(csv.DictReader(io.StringIO(text)))
v = [float(r["v"]) for r in rows]
```

**`np.loadtxt`**: fast, for clean numeric data.

```
data = np.loadtxt(io.StringIO(text), delimiter=",", skiprows=2)
t, v, i = data.T          # columns, by unpacking the transpose
```

`skiprows` counts every line from the top, comment lines included, so here it skips the comment and the header. (Comment lines further down are dropped automatically: `comments="#"` is the default.)

**`np.genfromtxt`**: like `loadtxt`, but turns missing or unreadable entries into `nan` (not a number) instead of failing.

```
data = np.genfromtxt(io.StringIO(text), delimiter=",", skip_header=1)
np.nanmean(data[:, 1])    # the mean, ignoring the nan entries
np.isnan(data).sum()      # how many entries were missing
```

## Writing CSV

```
lines = ["f,gain_db"] + [f"{fi:g},{gi:.3f}" for fi, gi in zip(f, g)]
text = "\n".join(lines)
```

or `csv.writer` for anything with quoting. Always write a header: a column of numbers with no name is useless six months later.

## Habits that prevent errors

- Print the first few rows and the shape before you analyze anything.
- Check units: a header like `i_mA` tells you to scale.
- Count missing values instead of silently dropping them.
:::

::: example
## Read the three-column log above and find the power at each sample.

::: solution
1. **Load the columns.** `skiprows=2` skips the comment line and the header, and `.T` splits the columns into `t`, `v` and `i`.
2. **Multiply.** The power at each sample is $v \times i$.

```
import io, numpy as np
text = """# logged 2026-11-18, channel A
t,v,i
0.000,0.00,1.000
0.001,0.95,0.905
0.002,1.81,0.819"""
t, v, i = np.loadtxt(io.StringIO(text), delimiter=",", skiprows=2).T
print(v * i)          # [0.      0.85975 1.48239]
```

3. **If the skip is wrong.** Get it wrong by one and `loadtxt` stops with a `ValueError` on the header, which is a safe way to fail.

**Answer:** the power at the three samples is 0, 0.85975 and 1.48239.
:::
:::

::: example
## A log has a missing value. Find the mean of each column anyway.

::: solution
1. **Read with `genfromtxt`.** The blank entry becomes `nan`.
2. **Average around the gap.** `np.nanmean` averages the three good values of `v`.

```
text = "t,v\n0,1.0\n1,\n2,1.2\n3,1.1"
data = np.genfromtxt(io.StringIO(text), delimiter=",", skip_header=1)
print(np.isnan(data).sum(), np.nanmean(data, axis=0))     # 1 [1.5 1.1]
```

**Answer:** one value is missing, and the column means are 1.5 for `t` and 1.1 for `v`.
:::
:::

::: check
kind: python
given: k = 0..2 int

## Read the CSV text in the starter with `csv.DictReader`. Set `names` to the list of header names, `n` to the number of data rows, and `vmax` to the largest value in the `v` column.

```python starter
import csv, io
text = ["t,v,i\n0,0.0,1.0\n1,0.6,0.8\n2,1.1,0.4\n3,0.9,0.1",
        "time,v,temp\n0,3.30,25\n10,3.28,31\n20,3.27,38",
        "t,i,v,p\n0,2,5,10\n1,2.1,4.8,10.08\n2,2.2,4.7,10.34\n3,2.0,5.1,10.2\n4,1.9,5.2,9.88"][k]
names = []
n = 0
vmax = 0
print(names, n, vmax)
```

```python solution
import csv, io
text = ["t,v,i\n0,0.0,1.0\n1,0.6,0.8\n2,1.1,0.4\n3,0.9,0.1",
        "time,v,temp\n0,3.30,25\n10,3.28,31\n20,3.27,38",
        "t,i,v,p\n0,2,5,10\n1,2.1,4.8,10.08\n2,2.2,4.7,10.34\n3,2.0,5.1,10.2\n4,1.9,5.2,9.88"][k]
reader = csv.DictReader(io.StringIO(text))
rows = list(reader)
names = reader.fieldnames
n = len(rows)
vmax = max(float(r["v"]) for r in rows)
print(names, n, vmax)
```

```python tests
want = [(["t", "v", "i"], 4, 1.1), (["time", "v", "temp"], 3, 3.30), (["t", "i", "v", "p"], 5, 5.2)][k]
assert list(names) == want[0], f"names should be {want[0]}: reader.fieldnames."
assert n == want[1], f"There are {want[1]} data rows."
assert abs(vmax - want[2]) < 1e-12, "vmax should be the largest value in the v column, as a float."
```
:::

::: check
kind: python
given: k = 0..2 int

## Load the numeric CSV in the starter with `np.loadtxt` (it starts with a comment line and a header). Set `t`, `v` to its first two columns and `avg` to the mean of `v`.

```python starter
import io
import numpy as np
text = ["# scope export\nt,v\n0,1.0\n0.5,1.5\n1.0,2.0\n1.5,1.5",
        "# run 7\nt,v,flag\n0,5.0,1\n1,4.9,1\n2,5.1,0\n3,5.0,1\n4,4.95,1",
        "# bench\nt,v\n0,-1\n1,0\n2,1\n3,0\n4,-1\n5,0"][k]
t = v = None
avg = 0
print(avg)
```

```python solution
import io
import numpy as np
text = ["# scope export\nt,v\n0,1.0\n0.5,1.5\n1.0,2.0\n1.5,1.5",
        "# run 7\nt,v,flag\n0,5.0,1\n1,4.9,1\n2,5.1,0\n3,5.0,1\n4,4.95,1",
        "# bench\nt,v\n0,-1\n1,0\n2,1\n3,0\n4,-1\n5,0"][k]
data = np.loadtxt(io.StringIO(text), delimiter=",", skiprows=2)
t, v = data[:, 0], data[:, 1]
avg = v.mean()
print(avg)
```

```python tests
import numpy as np
want_v = [[1.0, 1.5, 2.0, 1.5], [5.0, 4.9, 5.1, 5.0, 4.95], [-1, 0, 1, 0, -1, 0]][k]
assert v is not None and np.allclose(v, want_v), "v should be the second column. skiprows counts the comment line too, so skip 2 lines."
assert abs(avg - np.mean(want_v)) < 1e-12, "avg should be the mean of v."
```
:::

::: check
kind: python
given: k = 0..2 int

## The log in the starter has missing entries. Read it with `np.genfromtxt` and set `missing` to how many values are missing and `means` to the mean of each column, ignoring them.

```python starter
import io
import numpy as np
text = ["t,v,i\n0,1.0,0.5\n1,,0.4\n2,1.2,\n3,1.1,0.3",
        "t,v\n0,3.3\n1,3.2\n2,\n3,\n4,3.4",
        "a,b,c\n1,2,3\n,5,6\n7,,9\n10,11,"][k]
missing = 0
means = None
print(missing, means)
```

```python solution
import io
import numpy as np
text = ["t,v,i\n0,1.0,0.5\n1,,0.4\n2,1.2,\n3,1.1,0.3",
        "t,v\n0,3.3\n1,3.2\n2,\n3,\n4,3.4",
        "a,b,c\n1,2,3\n,5,6\n7,,9\n10,11,"][k]
data = np.genfromtxt(io.StringIO(text), delimiter=",", skip_header=1)
missing = int(np.isnan(data).sum())
means = np.nanmean(data, axis=0)
print(missing, means)
```

```python tests
import numpy as np
want_missing, want_means = [(2, [1.5, 1.1, 0.4]), (2, [2.0, 3.3]), (3, [6.0, 6.0, 6.0])][k]
assert missing == want_missing, f"missing should be {want_missing}: count with np.isnan(data).sum()."
assert means is not None and np.allclose(means, want_means), f"means should be {want_means}: np.nanmean(data, axis=0)."
```
:::

::: check
kind: python
given: fc = 100 | 200 | 500 | 1000 | 2000 | 5000

## Compute an RC low-pass's gain in dB at `f = [10, 100, 1000, 10000]` for `fc` = {fc} Hz, and set `text` to CSV with the header `f,gain_db` and the gains to three decimal places, one row per frequency, joined with `"\n"`.

```python starter
import numpy as np
f = [10, 100, 1000, 10000]
text = ""
print(text)
```

```python solution
import numpy as np
f = [10, 100, 1000, 10000]
g = [20 * np.log10(1 / np.sqrt(1 + (fi / fc)**2)) for fi in f]
text = "\n".join(["f,gain_db"] + [f"{fi},{gi:.3f}" for fi, gi in zip(f, g)])
print(text)
```

```python tests
import numpy as np
lines = text.strip().split("\n")
assert lines[0] == "f,gain_db", "The first line should be the header f,gain_db."
assert len(lines) == 5, "There should be a header and four rows."
for line, fi in zip(lines[1:], [10, 100, 1000, 10000]):
    a, b = line.split(",")
    assert float(a) == fi, "Each row starts with its frequency."
    assert b == f"{20 * np.log10(1 / np.sqrt(1 + (fi / fc)**2)):.3f}", "Write each gain with three decimals: {g:.3f}."
```
:::

::: check
kind: python
given: k = 0..2 int

## Each line of the starter's log looks like `12:00:05,3.301`: a time of day as `hh:mm:ss`, then a reading. Set `secs` to a list of each line's time in seconds since the first line, `vals` to the readings as floats, and `rate` to the average number of readings per second over the log (lines minus one, divided by the elapsed time).

```python starter
logs = ["12:00:00,3.301\n12:00:02,3.299\n12:00:04,3.305\n12:00:06,3.300",
        "23:59:50,1.20\n23:59:55,1.21\n00:00:00,1.19\n00:00:05,1.22\n00:00:10,1.20",
        "08:15:30,5.01\n08:15:31,5.02\n08:15:33,4.99\n08:15:34,5.00\n08:15:36,5.03\n08:15:37,5.01"]
lines = logs[k].split("\n")
secs = []
vals = []
rate = 0
print(secs, vals, rate)
```

```python solution
logs = ["12:00:00,3.301\n12:00:02,3.299\n12:00:04,3.305\n12:00:06,3.300",
        "23:59:50,1.20\n23:59:55,1.21\n00:00:00,1.19\n00:00:05,1.22\n00:00:10,1.20",
        "08:15:30,5.01\n08:15:31,5.02\n08:15:33,4.99\n08:15:34,5.00\n08:15:36,5.03\n08:15:37,5.01"]
lines = logs[k].split("\n")

def to_s(hms):
    h, m, s = (int(p) for p in hms.split(":"))
    return 3600 * h + 60 * m + s

secs, vals = [], []
t0 = None
for line in lines:
    when, value = line.split(",")
    t = to_s(when)
    if t0 is None:
        t0 = t
    if t < t0:
        t += 86400
    secs.append(t - t0)
    vals.append(float(value))
rate = (len(secs) - 1) / secs[-1]
print(secs, vals, rate)
```

```python tests
want_s = [[0, 2, 4, 6], [0, 5, 10, 15, 20], [0, 1, 3, 4, 6, 7]][k]
want_v = [[3.301, 3.299, 3.305, 3.300], [1.20, 1.21, 1.19, 1.22, 1.20], [5.01, 5.02, 4.99, 5.00, 5.03, 5.01]][k]
assert secs == want_s, f"secs should be {want_s}. If a time is earlier than the first, the log has passed midnight: add 86400 s."
assert vals == want_v, "vals should be the readings as floats."
assert abs(rate - (len(want_s) - 1) / want_s[-1]) < 1e-12, "rate is (number of readings - 1) / elapsed seconds."
```

::: right
Right. Splitting on `:` and `,` turns the text into numbers, and one of the logs runs past midnight, so the clock wraps from 23:59:55 to 00:00:00. Real logs do that, and code that assumes time only grows breaks once a day.
:::
:::

::: check
kind: choice

## What is `"3.3;4.7;5".split(";")`?

- [x] `['3.3', '4.7', '5']`, a list of strings
- [ ] `[3.3, 4.7, 5]`, a list of numbers
- [ ] `('3.3', '4.7', '5')`, a tuple
- [ ] An error, because `;` isn't a comma

::: right
Right. `split` cuts text into a list of smaller strings and never converts them. To get numbers, convert each one: `[float(s) for s in text.split(";")]`.
:::

::: misses
- [2] `split` only cuts the text. The pieces are still strings until you call `float` on each.
- [3] `split` returns a list.
- [4] `split` takes any separator you give it.
:::
:::

::: explain
## Why is it better to have a loader turn a missing value into `nan` than to skip the row or treat it as zero?

::: model
Treating it as zero puts a false measurement into the data and drags averages toward zero. Skipping the row silently changes how many samples there are and can misalign time stamps or other columns. Marking it as `nan` keeps the row and its other values, makes the gap visible so you can count and report it, and lets functions like `np.nanmean` leave it out of calculations deliberately.
:::
:::

::: practice

::: check
kind: python
given: k = 0..2 int

## Set `cols` to a dictionary from each header name to a list of floats for that column.

```python starter
import csv, io
text = ["a,b\n1,2\n3,4", "x,y,z\n0,1,2\n3,4,5\n6,7,8", "v\n1.5\n2.5\n3.5"][k]
cols = {}
print(cols)
```

```python solution
import csv, io
text = ["a,b\n1,2\n3,4", "x,y,z\n0,1,2\n3,4,5\n6,7,8", "v\n1.5\n2.5\n3.5"][k]
rows = list(csv.DictReader(io.StringIO(text)))
cols = {name: [float(r[name]) for r in rows] for name in rows[0]}
print(cols)
```

```python tests
want = [{"a": [1.0, 3.0], "b": [2.0, 4.0]}, {"x": [0.0, 3.0, 6.0], "y": [1.0, 4.0, 7.0], "z": [2.0, 5.0, 8.0]}, {"v": [1.5, 2.5, 3.5]}][k]
assert cols == want, f"cols should be {want}."
```
:::

::: check
kind: python
given: k = 0..1 int

## The column header says `i_mA`. Load the text and set `i` to the currents in amperes.

```python starter
import io
import numpy as np
text = ["t,i_mA\n0,1.5\n1,2.5\n2,0.5", "t,i_mA\n0,10\n1,20"][k]
i = None
print(i)
```

```python solution
import io
import numpy as np
text = ["t,i_mA\n0,1.5\n1,2.5\n2,0.5", "t,i_mA\n0,10\n1,20"][k]
i = np.loadtxt(io.StringIO(text), delimiter=",", skiprows=1)[:, 1] * 1e-3
print(i)
```

```python tests
import numpy as np
want = [[0.0015, 0.0025, 0.0005], [0.01, 0.02]][k]
assert i is not None and np.allclose(i, want), "Scale milliamps to amperes: multiply by 1e-3."
```
:::
:::
