Skip to content

The collections.namedtuple example opens a CSV file in binary mode #162868

Description

@XinYuDu-AI

Documentation URL

https://docs.python.org/3.15/library/collections.html#collections.namedtuple

Documentation

While reading the Python 3.15 documentation for collections.namedtuple, I noticed that the EmployeeRecord example opens employees.csv in binary mode and passes it to csv.reader. On Python 3, iterating over that file yields bytes, but csv.reader expects strings.

This line dates back to the Python 2.6 example. The Python 3.0 version updated the print statement but kept "rb", which is still present in the Python 3.15 docs.

Reproduction

Save the following row in employees.csv:

Alice,30,Engineer,Engineering,5

From the same directory, run the CSV portion of the documented example, with namedtuple imported:

from collections import namedtuple

EmployeeRecord = namedtuple('EmployeeRecord', 'name, age, title, department, paygrade')

import csv
for emp in map(EmployeeRecord._make, csv.reader(open("employees.csv", "rb"))):
    print(emp.name, emp.title)

The expected output is Alice Engineer. On CPython 3.15.2, the loop instead raises this error on the first row:

_csv.Error: iterator should return strings, not bytes (the file should be opened in text mode)

Running the full example, including the SQLite section, produces the same error before execution reaches import sqlite3.

Suggested fix

Open the file in text mode and pass newline="" so the CSV reader handles line endings. A with block also closes the file after iteration:

with open("employees.csv", newline="", encoding="utf-8") as f:
    for emp in map(EmployeeRecord._make, csv.reader(f)):
        print(emp.name, emp.title)

After spotting the issue, I used Codex to help work out the fix and test both versions locally on CPython 3.15.2. The corrected loop printed Alice Engineer for the same input.

Linked PRs

Activity

  1. added
    docs
    on Nov 30, 2026
  2. added a commit that references this issue on Nov 30, 2026
  3. added 2 commits that reference this issue on Nov 30, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    docs

    Projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions