LESSON · 1 OF 5

The csv module

The csv module

CSV is the format spreadsheets, billing exports, and monitoring dumps hand you: rows of values separated by commas, one record per line. It looks simple enough to split on commas yourself, but quoting and escaped values make that fragile. The standard library csv module handles the rules for you.

python
import csv

Reading rows with reader

csv.reader wraps an open file and yields one row at a time, each row a list of strings:

python
import csv

with open("/root/data/metrics.csv", newline="") as f:
    reader = csv.reader(f)
    for row in reader:
        print(row)

For a file starting host,cpu,mem, the first row comes back as ["host", "cpu", "mem"]. Every value is a string, so a number like 85 arrives as "85" and you convert it with int() when you need arithmetic.

Writing rows with writer

csv.writer goes the other way. writerow takes a list and writes it as one comma separated line:

python
import csv

with open("/root/data/out.csv", "w", newline="") as f:
    writer = csv.writer(f)
    writer.writerow(["host", "cpu"])
    writer.writerow(["web1", "85"])

Why newline=""

Notice newline="" on every open. The csv module manages line endings itself, and passing newline="" stops Python from adding extra blank lines between rows on some systems. Always open CSV files this way.

What this node introduces

  • csv.reader(f) yields each row as a list of strings.
  • csv.writer(f) writes rows; writerow takes a list for one line.
  • Open CSV files with newline="" so line endings are handled correctly.
Spin up a fresh environment and practice live.
python-devops · fresh machine · ready in under a minute