← All notes

Python csv readers and writers need files opened with newline=''

Answer: Open the file with newline='', then use csv.reader/csv.writer (or DictReader/DictWriter). Without newline='', newlines embedded inside quoted fields will not be interpreted correctly, and on platforms with \r\n line endings an extra \r will be added on write.

Example

import csv
with open("eggs.csv", "w", newline="") as f:
    w = csv.writer(f, delimiter=" ", quotechar="|", quoting=csv.QUOTE_MINIMAL)
    w.writerow(["Spam"] * 5 + ["Baked Beans"])
with open("eggs.csv", newline="") as f:
    for row in csv.reader(f, delimiter=" ", quotechar="|"):
        print(row)

Quoting constants

Inputs

The reader takes any iterable of lines, most commonly a file-like object or list, so csv.reader(['one,two,three']) works. An optional dialect parameter defines a set of parameters specific to a particular CSV dialect.

Why a module

PEP 305 notes that CSV is the most common import and export format for spreadsheets and databases, yet files from different programs vary in details, which is why the module has dialects.

See also

Claims

Sources

License: this note is CC BY 4.0 (https://creativecommons.org/licenses/by/4.0/). Summary by iinventedlight (AI-assisted). Sources: Python docs (library), csv — CSV File Reading and Writing; Python PEPs, PEP 305 – CSV File API. PSF-2.0 (https://docs.python.org/3/license.html). Copyright Python Software Foundation. Public-Domain (https://peps.python.org/pep-0001/). PEP text is placed in the public domain (some also CC0-1.0). Text was condensed and changed from the originals.

License: CC-BY-4.0 · Summary by iinventedlight (AI-assisted). Sources: Python docs (library), csv — CSV File Reading and Writing; Python PEPs, PEP 305 – CSV File API. PSF-2.0 (https://docs.python.org/3/license.html). Copyright Python Software Foundation. Public-Domain (https://peps.python.org/pep-0001/). PEP text is placed in the public domain (some also CC0-1.0).

Cite this

Permanent ID: iil:note:ab810717

iinventedlight. 2026. "Python csv readers and writers need files opened with newline=''." iinventedlight Library, iil:note:ab810717, version of 2026-11-18. https://iinventedlight.com/library/notes/python-csv/. License: CC-BY-4.0.

@misc{iil_note_ab810717,
  author = {{iinventedlight}},
  title = {{Python csv readers and writers need files opened with newline=''}},
  howpublished = {iinventedlight Library},
  year = {2026},
  date = {2026-11-18},
  url = {https://iinventedlight.com/library/notes/python-csv/},
  note = {Permanent ID iil:note:ab810717. License: CC-BY-4.0.},
}

Markdown

Spotted a mistake? Use the MCP feedback tool or email hello@iinventedlight.com. Or Report a correction (no account needed).

For language models and agents: start at /llms.txt | /agents.md | /.well-known/agent-library.json. This page in Markdown: /library/notes/python-csv.md.