CSV and TSV
CSV (comma-separated values) is the most common format for tabular data, and the one most likely to cause trouble. It is plain text: one line per row, values separated by commas, usually with a header line of column names. TSV is the same with a tab character as separator. Every tool can read and write them, people can open them in a text editor or a spreadsheet, and they compress well. But a CSV file stores no types, no units and no rules, so every reader has to guess.
Anatomy of a CSV file
id,name,city,amount
1,Ana,Hanoi,12.50
2,"Lee, Ben",Da Nang,7.00
3,"Cai ""the boss"" Tran",Hue,- The first line is the header.
- A value that contains a comma, a quote or a line break is wrapped in double quotes; a quote inside is written twice (
""). - An empty field (after the last comma on line 3) is a missing value.
There is a standard, RFC 4180, but many programs bend it. The Python standard library's csv module and pandas both follow the quoting rules:
import csv
import io
import pandas as pd
text = '''id,name,city,amount
1,Ana,Hanoi,12.50
2,"Lee, Ben",Da Nang,7.00
3,"Cai ""the boss"" Tran",Hue,
'''
for row in csv.reader(io.StringIO(text)):
print(row)
df = pd.read_csv(io.StringIO(text))
print()
print(df)
print(df.dtypes.to_dict())['id', 'name', 'city', 'amount']
['1', 'Ana', 'Hanoi', '12.50']
['2', 'Lee, Ben', 'Da Nang', '7.00']
['3', 'Cai "the boss" Tran', 'Hue', '']
id name city amount
0 1 Ana Hanoi 12.5
1 2 Lee, Ben Da Nang 7.0
2 3 Cai "the boss" Tran Hue NaN
{'id': dtype('int64'), 'name': dtype('O'), 'city': dtype('O'), 'amount': dtype('float64')}
csv.reader gives lists of strings, with no types at all. pandas guesses the types: id became integers, amount floats with NaN for the empty value. Splitting the lines on commas by hand (line.split(",")) would have cut "Lee, Ben" into two fields; always use a real CSV parser.
TSV and regional variants
Tab-separated files avoid most quoting, because tabs rarely appear inside values. Many European tools write CSV with a semicolon separator and a decimal comma, since the comma is already the decimal mark there:
import io
import pandas as pd
tsv = "id\tproduct\tprice\n1\tkettle\t19.99\n2\ttoaster, 2 slots\t24.50\n"
european = "id;product;price\n1;Wasserkocher;19,99\n2;Toaster;24,50\n"
a = pd.read_csv(io.StringIO(tsv), sep="\t")
b = pd.read_csv(io.StringIO(european), sep=";", decimal=",")
wrong = pd.read_csv(io.StringIO(european))
print(a, "\n")
print(b, "\n")
print("read with the defaults:", wrong.shape, list(wrong.columns)) id product price
0 1 kettle 19.99
1 2 toaster, 2 slots 24.50
id product price
0 1 Wasserkocher 19.99
1 2 Toaster 24.50
read with the defaults: (2, 1) ['id;product;price']
Read with the defaults, the European file becomes a single column, because pandas looked for commas between columns and found them inside the prices instead. Always check shape and columns right after reading a file.
Types are guesses
Because CSV is text, the reader decides what each column is, and the guesses can destroy information:
import io
import pandas as pd
text = """customer,zip,phone,signup,score
C001,01234,+49 30 1234,2026-03-01,7
C002,10115,+49 40 5678,2026-03-15,unknown
C003,00501,,01/04/2026,9
"""
naive = pd.read_csv(io.StringIO(text))
print(naive)
print(naive.dtypes.to_dict(), "\n")
careful = pd.read_csv(
io.StringIO(text),
dtype={"zip": "string", "phone": "string"},
na_values=["unknown"],
)
careful["signup"] = pd.to_datetime(careful["signup"], format="%Y-%m-%d", errors="coerce")
print(careful)
print(careful.dtypes.to_dict()) customer zip phone signup score
0 C001 1234 +49 30 1234 2026-03-01 7
1 C002 10115 +49 40 5678 2026-03-15 unknown
2 C003 501 NaN 01/04/2026 9
{'customer': dtype('O'), 'zip': dtype('int64'), 'phone': dtype('O'), 'signup': dtype('O'), 'score': dtype('O')}
customer zip phone signup score
0 C001 01234 +49 30 1234 2026-03-01 7.0
1 C002 10115 +49 40 5678 2026-03-15 NaN
2 C003 00501 <NA> NaT 9.0
{'customer': dtype('O'), 'zip': string[python], 'phone': string[python], 'signup': dtype('<M8[ns]'), 'score': dtype('float64')}
The naive read made three mistakes. The zip codes lost their leading zeros (01234 became 1234), because pandas saw digits and made them integers. The score column is text (object), because one value was unknown, which pandas does not know as a missing marker. (It does know a built-in list: an empty field, NA, n/a, NaN, null and a few more.) And signup stays text with two different date formats. The careful read declares the types, lists the missing-value marker, and parses dates with an explicit format, turning the odd date into NaT (missing) so that it shows up instead of being silently misread as 4 January or 1 April.
Writing CSV files
When you produce CSV for others (or for yourself next month), make it easy to read correctly:
import io
import pandas as pd
df = pd.DataFrame({
"zip": pd.Series(["01234", "10115"], dtype="string"),
"city": ["Dresden", "Berlin, Mitte"],
"temp_c": [21.5, None],
})
buf = io.StringIO()
df.to_csv(buf, index=False, na_rep="")
print(buf.getvalue())zip,city,temp_c
01234,Dresden,21.5
10115,"Berlin, Mitte",
index=Falseavoids an unnamed extra column of row numbers.- UTF-8 encoding, ISO dates (
2026-03-01), a dot as the decimal mark, and the unit in the column name (temp_c). - Ship a short data dictionary next to the file: column, type, unit, meaning, allowed values.
When CSV is the wrong choice
CSV is fine for small and medium tables that people want to open. For large datasets it is slow to parse, big on disk, and loses types every time it is read. Columnar binary formats such as Parquet keep the types and are many times faster. Nested data (lists inside fields) fits JSON better.
Practice
- A file has values like
"1.234,56"meaning one thousand two hundred thirty-four and 56 hundredths. Whichread_csvarguments read it correctly?
Answer
decimal="," and thousands=".", plus sep=";" if, as usual in such files, the columns are separated by semicolons.
- Why is
line.split(",")a bad CSV parser? Give a line that breaks it.
Answer
It ignores quoting. 2,"Lee, Ben",Da Nang gives four pieces instead of three, and a quoted value containing a line break would even split one row into two lines.
Test yourself
A zip code column 01234, 10115 is read by pandas without options. What happens to 01234?
- It stays
01234 - It becomes the integer 1234
- It becomes missing
- pandas raises an error
How is a value containing a comma stored in a standard CSV file?
- The comma is deleted
- The value is wrapped in double quotes
- The comma is replaced by a semicolon
- It cannot be stored
You read a CSV file and get a DataFrame with one column whose name contains semicolons. What is the likely cause?
- The file is corrupted
- The file uses
;as the separator, so you needsep=";" - The file is TSV
- The header is missing
What does CSV not store?
- Column names
- Column types, units and allowed values
- Missing values
- Text with commas