CSV ingestion
Import records from spreadsheet exports into backend or scripting workflows.
Python · Module
Python’s csv module reads and writes tabular data in CSV format, supporting both sequence rows and dictionary rows. Dialects and formatting parameters adapt it to different CSV conventions.
The csv module converts between CSV text and Python sequences or dictionaries. Use reader and writer for positional rows, or DictReader and DictWriter when column names should map to dictionary keys; dialect and formatting options control how fields are separated and quoted.
csv.reader(csvfile, dialect='excel', **fmtparams)
csv.writer(csvfile, dialect='excel', **fmtparams)
csv.DictReader(f, fieldnames=None, restkey=None, restval=None, dialect='excel', *args, **kwds)
csv.DictWriter(f, fieldnames, restval='', extrasaction='raise', dialect='excel', *args, **kwds)| Name | Type | Description |
|---|---|---|
csvfile | iterable | Input iterable or file-like object containing CSV lines. |
dialect | str or Dialect | Optional dialect name or dialect object controlling CSV formatting. |
fmtparams | keyword arguments | Additional formatting controls such as delimiter, quotechar, quoting, and lineterminator. |
reader() returns a reader object; writer() returns a writer object; DictReader yields dictionaries; DictWriter writes dictionary rows.
import csv
from io import StringIO
source = StringIO("name,age\nAda,36\nGrace,28\n")
rows = csv.DictReader(source)
output = StringIO()
writer = csv.DictWriter(output, fieldnames=["name", "age"])
writer.writeheader()
writer.writerows(rows)
print(output.getvalue(), end="")Reads CSV rows as dictionaries, then writes them with an explicit header.
Import records from spreadsheet exports into backend or scripting workflows.
Generate files compatible with spreadsheet applications and other CSV consumers.
Transform rows while retaining named columns for clearer application logic.
Use csv.reader for rows represented as sequences and csv.writer to emit sequences. Use DictReader and DictWriter when fields should be addressed by column names.
Follow-up: How would you preserve a supplied schema when writing? Pass fieldnames to DictWriter and call writeheader() before writerows().
A reader consumes lines from a CSV input and returns each row as a list of strings by default. A writer accepts row sequences and serializes them according to its dialect and formatting settings.
Follow-up: How can a reader use a nonstandard separator? Supply a dialect or a delimiter formatting parameter when constructing it.
DictReader maps values in each row to dictionary keys from fieldnames; if fieldnames are omitted, the first row supplies them. DictWriter maps dictionary keys to output columns named by its fieldnames argument.
Follow-up: What happens with dictionary keys that are not output fields? Configure the extrasaction option to control whether they are ignored or rejected.
DictReaderDictWriterDialectSnifferreaderwriterregister_dialectget_dialect