How to Read a TSV File
Read a TSV file without altering its data: inspect tabs and line endings, detect the dialect, parse it in Python, pandas or the shell, and verify the result.
A TSV (tab-separated values) file stores a table as plain text. To read one, you split each line into fields at the tab characters. The data can then be viewed, analyzed or imported without changing what it means. This guide explains how to inspect the file, detect its conventions, read it with common tools and confirm that nothing was altered along the way.
What a TSV file is and what reading it does
In a TSV file, each line is one record (a row). The fields in that row are separated by the tab character, Unicode U+0009. The first line often holds column names. Reading the file turns this text into rows and columns that a program or spreadsheet can work with. Reading alone never modifies the file. Changes happen only if a tool saves its interpretation back to disk.
Not every TSV file follows the same rules. The set of conventions a file uses is called its dialect. A dialect covers the delimiter, whether and how fields are quoted, the line ending, the character encoding and whether a header row is present. Three variations are common:
• Strict TSV has no quoting at all and simply does not allow tabs inside fields.
• Some files borrow CSV-style double quotes so that a field can contain a tab or a line break.
• Others use escape sequences such as a backslash followed by t.
Line endings may be LF (Unix style) or CRLF (Windows style). The encoding may be UTF-8, with or without a byte order mark (BOM), or an older legacy encoding.
Example file (illustrative). Tabs are invisible, so in this guide each tab is drawn as → in sample data. The real file contains a single tab character at each arrow.
id→name→zip
001→Ana López→02134
002→"Lee, J."→90210
Step 1: Inspect the raw file
Tabs and spaces look the same on screen, and line-ending characters are hidden. Look at the raw bytes before choosing settings. The commands below work in a Unix-like shell. The cat -et form works with both GNU and BSD cat: tabs show as ^I, each line end shows as $, and a carriage return shows as ^M just before the $.
head -n 5 data.tsv
cat -et data.tsv | head -n 5
file data.tsv # guesses encoding; mentions CRLF line terminators when present
- ^I between values: the delimiter really is a tab. Runs of spaces mean the file is space-aligned, not tab-separated.
- ^M$ at line ends: the file uses CRLF line endings.
- Double quotes around some values: the file may use CSV-style quoting, or the quotes may be literal data.
- M-oM-;M-? at the very start of the first line: a UTF-8 byte order mark is present.
- Whether the first line contains column names or data.
Step 2: Detect the dialect automatically
Python's built-in csv module includes csv.Sniffer. It guesses the delimiter and quoting style from a sample of text and estimates whether the first row is a header. The guess is a heuristic and can be wrong on small, irregular or mostly single-column samples. Treat the result as a suggestion and confirm it against your manual inspection. If sniff() cannot decide, it raises csv.Error.
import csv
with open("data.tsv", newline="", encoding="utf-8-sig") as f:
sample = f.read(64 * 1024)
sniffer = csv.Sniffer()
dialect = sniffer.sniff(sample, delimiters="\t,;|")
print(repr(dialect.delimiter), repr(dialect.quotechar), sniffer.has_header(sample))
In pandas, passing sep=None together with engine="python" applies the same sniffing approach. The same caution about checking the guess applies.
Step 3: Read the file in Python
- 1. Open the file with newline="". The csv module documentation recommends this so the reader handles line endings itself, including line breaks inside quoted fields.
- 2. Set the encoding explicitly. "utf-8-sig" reads UTF-8 and removes a leading BOM if one exists.
- 3. Pass delimiter="\t" to the reader.
- 4. Choose a quoting rule. Keep the default if the file uses CSV-style quotes. Use quoting=csv.QUOTE_NONE if double quotes are ordinary data.
- 5. Read the header, then compare every row's field count with it.
import csv
with open("data.tsv", newline="", encoding="utf-8-sig") as f:
reader = csv.reader(f, delimiter="\t")
header = next(reader)
for row in reader:
if len(row) != len(header):
print(f"line {reader.line_num}: expected {len(header)} fields, got {len(row)}")
# process row here
reader.line_num reports the physical line number in the source. It stays accurate even when a quoted field spans several lines. To treat quote characters as literal text, create the reader as csv.reader(f, delimiter="\t", quoting=csv.QUOTE_NONE). To get each row as a dictionary keyed by column name, use csv.DictReader with the same arguments.
Before and after: what a correct read looks like
Using the example file above with the default quoting rule, the documented behavior of the csv module should produce the rows below. This is an illustration of expected output, not a captured test run.
['id', 'name', 'zip']
['001', 'Ana López', '02134']
['002', 'Lee, J.', '90210']
With quoting=csv.QUOTE_NONE, the third row would instead keep the quotes as part of the value: '"Lee, J."'. Neither result is wrong in itself. The correct one depends on whether the producer of the file meant the quotes as quoting or as data.
- Result check:
- Every row has the same number of fields as the header.
- Values such as 001 and 02134 still have their leading zeros.
- Accented characters display correctly. Text like "López" means UTF-8 was decoded as Latin-1 or Windows-1252.
- The first header name has no stray prefix such as \ufeff or , which would indicate an unstripped BOM.
- The last field of each row does not end in \r.
Reading a TSV file with pandas
import pandas as pd
df = pd.read_csv(
"data.tsv",
sep="\t",
dtype=str, # keep every value as text, preserving leading zeros
keep_default_na=False, # don't turn "NA", "null" or empty cells into missing values
encoding="utf-8-sig",
)
print(df.shape)
print(df.head())
By default, pandas infers column types and recognizes certain strings as missing values. Under those defaults, 001 can become the number 1 and a literal "NA" can become an empty value. Reading everything as text first avoids silent changes; convert specific columns afterward on purpose. pd.read_table is an alternative that uses a tab separator by default. If the file's quotes are literal data, pass quoting=csv.QUOTE_NONE after importing csv. Compare df.shape against the line count you expect, minus the header.
Reading a TSV file on the command line
cut -f 2 data.tsv # cut splits on tab by default
awk -F'\t' '{ print $1, $3 }' data.tsv
awk -F'\t' '{ print NF }' data.tsv | sort | uniq -c # how many lines have each field count
column -t -s $'\t' data.tsv | less -S # align columns for viewing
These tools split on every tab and do not understand quoting. A quoted field that contains a tab or a line break will be broken apart. They are reliable only for strict TSV. The field-count command is a quick structure check: a healthy file shows a single count. Some versions of column merge adjacent tabs, which hides empty fields, so use column only for viewing and not for judging structure. The $'\t' form is bash and zsh syntax for a literal tab.
If the file has CRLF line endings, these tools leave a carriage return at the end of the last field. Write a cleaned copy rather than editing the original. Note that tr removes every carriage return in the file, including any inside fields. The awk version removes only the one at each line end.
awk '{ sub(/\r$/, ""); print }' data.tsv > data_lf.tsv
# or, removing all carriage returns:
tr -d '\r' < data.tsv > data_lf.tsv
Opening a TSV file in a spreadsheet
Opening a TSV file directly in a spreadsheet application lets it convert values automatically. Common changes:
• Leading zeros are dropped.
• Long digit strings are shown in scientific notation.
• Date-like text is turned into dates.
Use the application's text or data import feature instead. Choose Tab as the delimiter, select the correct encoding (usually UTF-8) and set sensitive columns such as IDs, ZIP codes and phone numbers to Text. Menu names differ between applications and versions, and no product-specific steps were supplied for this guide. Do not save over the original TSV after an automatic conversion: digits removed in that save cannot be recovered from the saved file.
Common problems and fixes
| Symptom | Likely cause | Fix |
| Everything lands in one column | Delimiter is spaces or commas, not tabs | Inspect with cat -et and set the real delimiter |
| Accents appear garbled (López) | UTF-8 decoded as Latin-1 or Windows-1252 | Specify the encoding as UTF-8 |
| First header name starts with \ufeff or  | Byte order mark not stripped | Use the utf-8-sig encoding in Python |
| Last column ends with \r or shows ^M | CRLF line endings read as LF | Use newline="" in Python; strip \r into a copy for shell tools |
| Some rows have extra fields | Unquoted tab inside a value, or a quote-unaware tool splitting a quoted field | Check the quoting convention; use a csv-aware reader |
| Rows merge or field counts go wrong after a quote mark | A literal quote is being treated as the start of a quoted field | Read with quoting=csv.QUOTE_NONE |
| Leading zeros are missing | Automatic number conversion | Read columns as text |
| "NA" or "null" became missing values | Missing-value detection in pandas | Set keep_default_na=False |
Keeping the original data intact
- Reading is non-destructive. Risk comes only from saving, so write any cleaned or converted output to a new file.
- Avoid in-place edits such as sed -i on the only copy. Make a backup first.
- To confirm the source was not touched, record a checksum before and after your work. The two values should match.
- Keep the raw file alongside any processed version so you can return to it if a conversion turns out to be wrong.
sha256sum data.tsv # on macOS: shasum -a 256 data.tsv
Evidence gaps
No specific tool versions, sample files or test results were supplied for this guide. The commands and outputs shown are illustrative and were not run here. Parameter names and defaults can change between releases of Python, pandas, shell utilities and spreadsheet software. Before relying on an example in a production workflow, check it against the documentation for the version you use and test it on a copy of your file.