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.0Writing 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.
- Import
csv. - Open
employees.csvin read mode. Create acsv.DictReadernamedreader. Create a list namedhigh_earnersusing a list comprehension that includes eachrowfromreaderwhereint(row["salary"]) > 70000. - Open
high_earners.csvin write mode withnewline="". Create acsv.DictWriternamedwriterwithfieldnames=["name", "department", "salary"]. Callwriter.writeheader(). Callwriter.writerows(high_earners). - Call
print(f"Found {len(high_earners)} high earners."). - Call
print("Saved to high_earners.csv.").
# employees.csv contains: # name,department,salary # Alice,Engineering,85000 # Bob,Marketing,62000 # Charlie,Engineering,91000 # Dana,Marketing,58000 # Step 1: Import csv # Step 2: Read employees.csv and filter rows where salary > 70000 into high_earners # Step 3: Write high_earners to high_earners.csv with headers # Step 4: Print number of high earners found # Step 5: Print "Saved to high_earners.csv."
Interactive Code Editor
Sign in to write and run code, track your progress, and unlock all chapters.
Sign In to Start Coding