Filtering & Transforming Rows
Exit

Filtering & Transforming Rows

Read CSV data, filter rows by condition, and write the results

💻

Writing code and entering commands is only available on desktop. Open this page on a larger screen to complete this chapter.

Processing CSV data

A common pattern is to read a CSV file, filter or transform the rows, then write the results to a new file. This keeps the original data intact and produces a clean output file.

import csv

with open("input.csv", "r") as file:
    reader = csv.DictReader(file)
    filtered = [row for row in reader if condition]

Type conversion

CSV stores everything as strings. When you filter on numeric values, convert the string first.

int(row["salary"]) > 70000   # convert before comparing
float(row["price"]) < 10.0

Writing filtered results

After filtering, write the results to a new CSV using DictWriter. Use the same fieldnames as the original file.

Instructions

Filter high-earning employees from a CSV file and write the results to a new file.

  1. Import csv.
  2. Open employees.csv in read mode. Create a csv.DictReader named reader. Create a list named high_earners using a list comprehension that includes each row from reader where int(row["salary"]) > 70000.
  3. Open high_earners.csv in write mode with newline="". Create a csv.DictWriter named writer with fieldnames=["name", "department", "salary"]. Call writer.writeheader(). Call writer.writerows(high_earners).
  4. Call print(f"Found {len(high_earners)} high earners.").
  5. Call print("Saved to high_earners.csv.").