Sniff CSV Delimiters and Read Rows
Detect a CSV delimiter and quote style from a sample, then parse rows into dictionaries without hard-coding comma assumptions.
Code
import csv
import io
def detect_dialect(sample: str) -> dict[str, object]:
dialect = csv.Sniffer().sniff(sample, delimiters=",;\t|")
return {
"delimiter": dialect.delimiter,
"quotechar": dialect.quotechar,
"doublequote": dialect.doublequote,
"skipinitialspace": dialect.skipinitialspace,
}
def read_rows(text: str) -> list[dict[str, str]]:
dialect = csv.Sniffer().sniff(text, delimiters=",;\t|")
reader = csv.DictReader(io.StringIO(text), dialect=dialect)
return [dict(row) for row in reader]
if __name__ == "__main__":
sample = "name;role;city\nAda;engineer;London\nGrace;admiral;New York\n"
print(detect_dialect(sample))
print(read_rows(sample))
Output
Captured from a sandboxed run of this snippet in the build pipeline.
{'delimiter': ';', 'quotechar': '"', 'doublequote': False, 'skipinitialspace': False}
[]How the snippet works
Structurally, expect the functions detect_dialect and read_rows and nothing else.
The result is a fresh construction, so callers can keep their originals.
What to watch for
- Plan for an install step:
csvis a real dependency, resolved by the package manager.
Applying it
The primary signature is def detect_dialect(sample: str) -> dict[str, object]
Statements that matter
def detect_dialect(sample: str) -> dict[str, object]:
dialect = csv.Sniffer().sniff(sample, delimiters=",;\t|")
return {
"delimiter": dialect.delimiter,
"quotechar": dialect.quotechar,
"doublequote": dialect.doublequote,
"skipinitialspace": dialect.skipinitialspace,
}
def read_rows(text: str) -> list[dict[str, str]]:
dialect = csv.Sniffer().sniff(text, delimiters=",;\t|")
reader = csv.DictReader(io.StringIO(text), dialect=dialect)
return [dict(row) for row in reader]
Interactive Tools for This Topic
CSV Column AnalyzerProfile every CSV column with inferred types, empty-cell counts, unique values, and numeric min and max ranges.CSV to JSON ConverterConvert comma-separated values into a JSON array of objects using the first row as field names, with support for quoted and escaped fields.CSV to Markdown TableConvert CSV data, including quoted fields with embedded commas and newlines, into a clean GitHub-flavored Markdown table with selectable alignment.CSV to TSV ConverterParse RFC 4180 CSV with quoted fields and re-serialize using a tab, pipe, semicolon, or custom delimiter, with optional quoting.
FAQ
- Does `detect_dialect` modify its input?
- No mutation happens — the function reads its input and returns a new value.
- How do you run Sniff CSV Delimiters and Read Rows?
- This is a complete program, not a library excerpt — execution starts at the top.
Report a problem with this exampleOpens a pre-filled issue on GitHub.