csv module
csv files
Python programming
data processing
read specific columns

Read specific columns from a csv file with csv module?

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

Introduction

If you want only a few columns from a CSV file, Python's built-in csv module is enough. The usual choice is csv.DictReader when the file has headers, because it lets you select columns by name instead of by fragile numeric position.

Use DictReader when the file has headers

DictReader converts each row into a dictionary keyed by the header row. That makes selective reading simple and readable.

python
1import csv
2from pathlib import Path
3
4path = Path("people.csv")
5path.write_text(
6    "name,age,city\nAlice,30,Toronto\nBob,25,Montreal\n",
7    encoding="utf-8",
8)
9
10with path.open("r", newline="", encoding="utf-8") as handle:
11    reader = csv.DictReader(handle)
12    for row in reader:
13        print(row["name"], row["city"])

This is usually the best answer when you know the column names and want code that survives column reordering.

Build a smaller result explicitly

If you want each output row to contain only selected fields, build a new dictionary rather than carrying around the full row.

python
1import csv
2
3columns = ["name", "city"]
4records = []
5
6with open("people.csv", "r", newline="", encoding="utf-8") as handle:
7    reader = csv.DictReader(handle)
8    for row in reader:
9        records.append({column: row[column] for column in columns})
10
11print(records)

That pattern is convenient when you are preparing data for JSON output, validation, or downstream processing.

Use positional indexes only when headers are missing

If the CSV has no header row, use csv.reader and numeric indexes instead.

python
1import csv
2from pathlib import Path
3
4path = Path("sales.csv")
5path.write_text(
6    "101,Alice,49.5\n102,Bob,75.0\n",
7    encoding="utf-8",
8)
9
10with path.open("r", newline="", encoding="utf-8") as handle:
11    reader = csv.reader(handle)
12    for row in reader:
13        customer = row[1]
14        amount = float(row[2])
15        print(customer, amount)

This works, but it is more brittle. If someone inserts a new column, your index assumptions break immediately.

Guard against missing columns

Real CSV files are messy. A file may have misspelled headers, optional columns, or extra whitespace. If the data source is not fully controlled, validate the headers before processing.

python
1import csv
2
3required = {"name", "city"}
4
5with open("people.csv", "r", newline="", encoding="utf-8") as handle:
6    reader = csv.DictReader(handle)
7    missing = required - set(reader.fieldnames or [])
8    if missing:
9        raise ValueError(f"Missing columns: {sorted(missing)}")
10
11    for row in reader:
12        print(row["name"], row["city"])

That small check makes failures immediate and understandable instead of producing confusing KeyError messages halfway through processing.

Read large files row by row

The csv module is already stream-friendly. You do not need to load the whole file into memory just to extract two columns. Iterate row by row and emit only the values you need.

This matters for export files, log archives, and one-time migration scripts. Selective reading is often more about memory discipline than raw speed.

Remember that CSV values are strings

The csv module returns text. If a selected column represents numbers, dates, or booleans, convert those values explicitly. That keeps the code honest and avoids hidden assumptions later.

A selective read is still a parsing step, not just a slicing step.

Common Pitfalls

  • Using numeric indexes on header-based files when DictReader would be clearer and safer.
  • Forgetting newline="" when opening CSV files, which can cause blank-line issues on some platforms.
  • Assuming selected values already have the right type instead of converting them explicitly.
  • Ignoring missing or misspelled headers and failing later with KeyError.
  • Loading the whole file into a list when a row-by-row loop is enough.

Summary

  • Use csv.DictReader to read specific columns by header name.
  • Build a smaller dictionary when you only want selected fields in the output.
  • Use positional indexes only when the CSV has no headers.
  • Validate headers before processing uncontrolled files.
  • Convert selected values explicitly because the csv module reads everything as strings.

Related reading
Free course
Beginner
7 lessons
2 hours
Tackling System Design Interview Problems

A short course that equips you with the skills to approach system design interviews methodically.

Start the free course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

All Rights Reserved.