Writing CSV in Python
DictWriter takes rows as dicts and writes the header for you.
import csv
from io import StringIO
rows = [
{"lang": "python", "tpm": 104, "stars": 3},
{"lang": "rust", "tpm": 98, "stars": 3},
]
buffer = StringIO()
writer = csv.DictWriter(buffer, fieldnames=["lang", "tpm", "stars"],
extrasaction="ignore")
writer.writeheader()
writer.writerows(rows)
print(buffer.getvalue())
print(list(csv.DictReader(StringIO(buffer.getvalue())))[0])
How it works
newline=empty is required, or you get blank lines on Windows.writeheaderemits the field names once.extrasactiondecides what to do with keys you did not declare.
Keywords and builtins used here
listprint
The run, in numbers
- Lines
- 16
- Characters to type
- 374
- Tokens
- 130
- Three-star pace
- 105 tpm
At the three-star pace of 105 tokens a minute, this run takes about 74 seconds.
Step 4 of 4 in Files & archives, step 29 of 41 in Domain tools.