Practical data workflows
Export results reproducibly
Write a stable, readable summary file.
Lesson 62 of 63
Reading: about 1 min
Lesson + practice: about 16 min
Difficulty: Intermediate
On this page5 sections
Sort keys before writing when a stable output order matters. Specify UTF-8 and a newline so repeated runs produce the same text.
Worked example
import csv
from pathlib import Path
totals = {"SQL": 25, "Python": 50}
with Path("summary.csv").open("w", newline="", encoding="utf-8") as file:
writer = csv.writer(file)
writer.writerow(["subject", "minutes"])
for subject in sorted(totals):
writer.writerow([subject, totals[subject]])
print(Path("summary.csv").read_text(encoding="utf-8"), end="")subject,minutes Python,50 SQL,25
Why this works
Sorting avoids dependence on input order. Opening in write mode replaces a previous output, which makes reruns predictable. csv.writer quotes fields when needed.
Another case
import csv
from io import StringIO
buffer = StringIO()
writer = csv.writer(buffer)
writer.writerow(["Data, science", 5])
print(buffer.getvalue().strip())"Data, science",5
Practice
Change SQL to 30, rerun, and inspect summary.csv.
Check the practice result
Reveal answer
It should contain SQL,30 and no duplicate old row.
Try another case
Why sort the subjects before writing instead of using the dictionary order?
Check your answer
Reveal answer
Dictionary order follows insertion order, which depends on the input. Sorting makes the file identical on every run, whatever order the data arrived in.
Your progress
Reveal the check answer or reach the end to complete this lesson.