Python Glossary Русский

all Python 3Files & I/Oterm

csv.Sniffer

csv — utilities

Guesses the CSV format from a text sample: sniff() returns a dialect with the detected delimiter, and has_header() says whether there is a header row.

Syntax

dialect = csv.Sniffer().sniff(sample, delimiters=None); csv.Sniffer().has_header(sample)

It is a heuristic and errs both ways: on a short or uniform sample the delimiter or header can be guessed wrong, and on a bad sample sniff() raises csv.Error. Pass a chunk of the file (say, the first few kilobytes), and seek(0) after reading it, or the reader starts in the middle. If you know the format, set delimiter explicitly.

Examples

import csv
import io
f = io.StringIO('name;age\nAnna;30\nBob;25\n')
sample = f.read(1024)
dialect = csv.Sniffer().sniff(sample)
print(repr(dialect.delimiter), csv.Sniffer().has_header(sample))  # → ';' True
f.seek(0)
print(list(csv.reader(f, dialect))[1])  # → ['Anna', '30']

See also

Open in the full glossarydocs.python.orgReport an inaccuracy