Sort records and write a CSV file
Read named columns, convert types, and write sorted rows.
Jump to the automation labOpen CSV files with newline="" and specify an encoding. csv.DictReader handles quoted commas and maps values to the header names. csv.DictWriter takes a list of fields and writes values in that order.
Use sorted(rows, key=...) to describe the value to compare for each record. CSV fields start as strings, so convert numeric fields before sorting. Otherwise "10" sorts before "2". A tuple key can break ties with a secondary column.
The quoted comma is part of the station name.
Run the example and practice
Sort by count from highest to lowest. Break ties by station name without regard to case. Keep the header and all rows.
Target output
station,count
Elm,9
"Harbor, East",9
Pine,2Show a hint
Use a two-part key. Negate the integer count to get descending counts while keeping names ascending.
Ready
Run your code to see the output here.
Check output also tests your code with additional cases.
The first run downloads Python. Code runs in your browser. Progress and drafts are stored on this device.
Show one solution
import csv
from pathlib import Path
source = Path("stations.csv")
source.write_text(
'station,count\nPine,2\n"Harbor, East",9\nElm,9\n',
encoding="utf-8",
)
def order_stations(rows):
return sorted(rows, key=lambda row: (-int(row["count"]), row["station"].casefold()))
with source.open(encoding="utf-8", newline="") as file:
rows = order_stations(csv.DictReader(file))
report = Path("ordered.csv")
with report.open("w", encoding="utf-8", newline="") as file:
writer = csv.DictWriter(file, fieldnames=["station", "count"])
writer.writeheader()
writer.writerows(rows)
print(report.read_text(encoding="utf-8"), end="")Automation lab
Rank tasks from a spreadsheet export
Sort exported rows by numeric priority and use the title to break ties.
Ready
Run the example to see the output here.
Sort the values as strings once and compare the result for priority 2 versus 10.
Further reading in Automate the Boring Stuff with Python by Al Sweigart