brewedbits.dev

Personal blog with guides and news on selfhosting, Linux and AI, from the Netherlands

nextDash nextdash --aboutYour bookmarks. Your terminal. checks your links knows your Docker host one container, no cloudLive demo →nextdash.cc ↗

Tip: csv.Sniffer guesses the delimiter of a CSV file

Csv
~/tips/tip-python-csv-sniffer-delimiter

import csv

Looks at a sample of a CSV file and returns the dialect, so you don't have to know the delimiter.

Some CSV files use commas, some semicolons, some tabs, and the file name never tells you which. Python’s standard library can take a guess for you.

import csv

with open("export.csv", newline="") as f:
    dialect = csv.Sniffer().sniff(f.read(1024))
    f.seek(0)
    for row in csv.reader(f, dialect):
        print(row)

This is the pattern from the Python docs. sniff() analyzes a sample and returns a Dialect subclass, and you hand that to csv.reader. Remember the seek(0), because reading the sample moved the file position.

On Python 3.11, the small samples name;city, name,city and name<TAB>city (each followed by a row of data) gave ';', ',' and '\t'. If you already know the candidates, pass them: sniff(sample, delimiters=";,"). The docs add that when several delimiters fit equally well, the ones in the preferred list win, in the order comma, tab, semicolon, space, colon.

The caveat is that it is a guesser. The docs call has_header() a rough heuristic that can be wrong in both directions, and on the tiny samples above it returned False although every file had a header row. The delimiter can be wrong too: a one-column sample like abc gave 'c', and an empty string raised csv.Error: Could not determine delimiter.

So I’d use it for a quick look at files of unknown origin, with a large enough sample and a print of the first rows to check. For a file you control, set the delimiter explicitly.

Further reading: Python csv module: Sniffer

Going deeper: Moving on from hdtv: how to export your TV show list to Trakt.tv

More Csv tips \copy (SELECT id, email FROM users WHERE active) TO 'users.csv' WITH (FORMAT csv, HEADER) All Csv tips (2) All topics

Link