How to Read a TSV File in Python with csv.DictReader

Read a tab-separated (TSV) file into dictionaries using the csv module's DictReader with a tab delimiter.

Easy Python 3.9+ Aug 9, 2026 Files & data 15 views 0 copies

Python code

21 lines
Python 3.9+
import csv
from pathlib import Path

data_file = Path("data.tsv")

# Sample TSV content (tab-separated)
sample = """name\tage\tcity
Alice\t30\tNew York
Bob\t25\tLos Angeles
Carol\t35\tChicago
"""
data_file.write_text(sample)

with data_file.open("r", newline="", encoding="utf-8") as f:
    reader = csv.DictReader(f, delimiter="\t")
    rows = list(reader)

for row in rows:
    print(f"{row['name']} is {row['age']} from {row['city']}")

print(f"Total rows: {len(rows)}")

Output

stdout
Alice is 30 from New York
Bob is 25 from Los Angeles
Carol is 35 from Chicago
Total rows: 3

How it works

The csv.DictReader treats the first row as headers and returns each subsequent row as a dictionary mapping headers to cell values. Setting delimiter="\t" makes it parse tab-separated files instead of the default comma. Opening the file with newline="" prevents the csv module from seeing extra line breaks that can corrupt parsing. Using pathlib.Path gives clean file handling with context managers, and encoding="utf-8"" ensures proper Unicode support.

Common mistakes

  • Forgetting to set delimiter="\t" — the default comma will split each line into a single field.
  • Opening the file without newline="" can cause embedded newlines to be misinterpreted.
  • Assuming all rows have the same number of columns without validating the data.

Variations

  1. Use `csv.reader(f, delimiter="\t")` to get lists instead of dictionaries.
  2. Read the file with `pandas.read_csv('data.tsv', sep='\t')` if pandas is already a dependency.

Real-world use cases

  • Importing product catalogs or export files from spreadsheets into a database pipeline.
  • Responding to a client's request for a TSV dump of user data so it can be loaded into their analytics.
  • Parsing daily transactional logs from a legacy system that exports tab-separated files.

Sponsored

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Files & data

Related tutorials and quizzes for this topic.