csv — CSV reading and writing

Python csv reader and writer, including the official newline='' file mode and the fact that fields are strings, not inferred types.

モジュールページの本文は現在英語です。

The csv module is part of the Python standard library. It is not a built-in and not a third-party package. Import it with `import csv`. Official documentation requires that a file object used as a CSV file be opened with newline=''. That setting disables universal-newline translation so the module can handle line endings itself. On Windows, omitting it can produce extra blank lines because the writer already emits \r\n.

Reader APIs do not infer types. A numeric-looking field comes back as a string. This page covers writer, reader, and DictReader. It does not cover every dialect option.

Examples were checked against Python 3.13. See the official documentation for the complete API.

Python reference overview →

writer, reader, and newline

csv.writer(file) writes rows to a file-like object. csv.reader(file) iterates rows as lists of strings. The default excel dialect uses a comma delimiter, quotes fields when needed, and uses \r\n as the line terminator even on Unix.

The examples below write to a temporary directory and open the file with newline=''. They do not make network requests.

csv.writer, csv.reader

csv.writer(csvfile, dialect='excel', **fmtparams)
csv.reader(csvfile, dialect='excel', **fmtparams)

Write and read CSV rows. Open the file with newline=''. Values written as integers are still read back as strings.

ParameterDescription
csvfileA file-like object. For a real file, open it with newline='' as required by the official documentation.
dialectA registered dialect name or a dialect object. The default is excel.

Returns: writer returns a writer object with writerow and writerows. reader returns an iterator of rows, each a list of strings.

  • A field that contains a comma is quoted, as in "Grace, Hopper".
  • path.read_bytes() shows the dialect's \r\n terminators. Text mode without newline='' would translate those endings on some platforms, which is why the official guidance is to use newline=''.
  • The integer 2 is written in the second column, but the reader returns the string '2'. The csv module does not infer int or float.
python
import csv
import tempfile
from pathlib import Path

with tempfile.TemporaryDirectory() as tmp:
    path = Path(tmp) / "rows.csv"
    with path.open("w", newline="") as file:
        writer = csv.writer(file)
        writer.writerow(["name", "count"])
        writer.writerow(["Ada", 2])
        writer.writerow(["Grace, Hopper", 3])
    with path.open("r", newline="") as file:
        print(repr(file.read()))
        file.seek(0)
        rows = list(csv.reader(file))
    print(rows)
    print(type(rows[1][1]).__name__, rows[1][1])

Expected output

'name,count\r\nAda,2\r\n"Grace, Hopper",3\r\n'
[['name', 'count'], ['Ada', '2'], ['Grace, Hopper', '3']]
str 2

Official documentation →

DictReader and string fields

DictReader uses the first row as field names by default and yields a dict for each later row. The values are still strings. If you need an int or a float, convert the field yourself after reading.

csv.DictReader

csv.DictReader(f, fieldnames=None, restkey=None, restval=None, dialect='excel', *args, **kwds)

Read each CSV row as a dictionary keyed by the header. Field values remain strings; the module does not infer Python types.

ParameterDescription
fA file-like object opened with newline='' when it is a regular file.
fieldnamesOptional column names. If omitted, the first row is used as the header and is not yielded as data.

Returns: An iterator of dicts (dict[str, str] in ordinary cases). Missing fields are filled with restval; extra fields are collected under restkey if you set it.

  • dicts[0]["count"] is the string '2', not the integer 2, even though the writer was given an integer.
python
import csv
import tempfile
from pathlib import Path

with tempfile.TemporaryDirectory() as tmp:
    path = Path(tmp) / "rows.csv"
    with path.open("w", newline="") as file:
        writer = csv.writer(file)
        writer.writerow(["name", "count"])
        writer.writerow(["Ada", 2])
        writer.writerow(["Grace, Hopper", 3])
    with path.open("r", newline="") as file:
        rows = list(csv.DictReader(file))
    print(rows)
    print(type(rows[0]["count"]).__name__, rows[0]["count"])

Expected output

[{'name': 'Ada', 'count': '2'}, {'name': 'Grace, Hopper', 'count': '3'}]
str 2

Official documentation →