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.
import csv
csv.reader wraps an open file and yields one row at a time, each row a
list of strings:
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.
csv.writer goes the other way. writerow takes a list and writes it
as one comma separated line:
import csv
with open("/root/data/out.csv", "w", newline="") as f:
writer = csv.writer(f)
writer.writerow(["host", "cpu"])
writer.writerow(["web1", "85"])
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.
csv.reader(f) yields each row as a list of strings.csv.writer(f) writes rows; writerow takes a list for one line.newline="" so line endings are handled correctly.