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.
Python code
21 linesimport 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
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
- Use `csv.reader(f, delimiter="\t")` to get lists instead of dictionaries.
- 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
More from Files & data
- Append a Line to a Log File in Python easy
- Audit File Permissions Across a Project in Python easy
- Automatically Detect Corrupted Files Using SHA-256 Checksums in Python easy
- Automatically Highlight Data Validation Errors Inside Excel Files in Python easy
- Build a Command-Line To-Do List Application with Data Persistence in Python easy
- Build a File Index by Relative Path Hash Map in Python easy
Keep learning
Related tutorials and quizzes for this topic.