CKTIS / Python
csv.Sniffer
Infers likely CSV formatting from sample text and returns a dialect.
Version: Python 3.14; repository image, production runtime not attested
Syntax
csv.Sniffer().sniff(sample, delimiters=None)Infers likely CSV formatting from sample text and returns a dialect.
Inference depends on representative rows. Restricting candidate delimiters can prevent unrelated punctuation from being chosen.
Infer a dialect from a representative text sample. delimiters restricts the single-character candidates and csv.Error means no candidate was inferred. has_header is a separate heuristic that can be wrong. When reading a sample from a file, rewind before parsing the complete file. The example selects semicolon and reads the header as a regular row.
import csv
s = csv.Sniffer()
dialect = s.sniff("a;b\n1;2\n", delimiters=",;")
assert dialect.delimiter == ";"
try:
s.sniff("aaa\nbbb\n", delimiters=",;")
except csv.Error:
pass
else:
raise AssertionError
Examples
import csv
sample = "id;qty\n3;8\n4;9\n"
dialect = csv.Sniffer().sniff(sample, delimiters=",;")
print(dialect.delimiter)
print(list(csv.reader(sample.splitlines(), dialect)))
Result
; [['id', 'qty'], ['3', '8'], ['4', '9']]
Infer a dialect from a representative text sample. delimiters restricts the single-character candidates and csv.Error means no candidate was inferred. has_header is a separate heuristic that can be wrong. When reading a sample from a file, rewind before parsing the complete file. The example selects semicolon and reads the header as a regular row.