python/cpython · error · ValueError

file should be opened in binary mode

Error message

file should be opened in binary mode

What it means

Error "file should be opened in binary mode" thrown in python/cpython.

Source

Thrown at Lib/asyncio/base_events.py:999

            while True:
                if count:
                    blocksize = min(count - total_sent, blocksize)
                    if blocksize <= 0:
                        break
                view = memoryview(buf)[:blocksize]
                read = await self.run_in_executor(None, file.readinto, view)
                if not read:
                    break  # EOF
                await self.sock_sendall(sock, view[:read])
                total_sent += read
            return total_sent
        finally:
            if total_sent > 0 and hasattr(file, 'seek'):
                file.seek(offset + total_sent)

    def _check_sendfile_params(self, sock, file, offset, count):
        if 'b' not in getattr(file, 'mode', 'b'):
            raise ValueError("file should be opened in binary mode")
        if not sock.type == socket.SOCK_STREAM:
            raise ValueError("only SOCK_STREAM type sockets are supported")
        if count is not None:
            if not isinstance(count, int):
                raise TypeError(
                    "count must be a positive integer (got {!r})".format(count))
            if count <= 0:
                raise ValueError(
                    "count must be a positive integer (got {!r})".format(count))
        if not isinstance(offset, int):
            raise TypeError(
                "offset must be a non-negative integer (got {!r})".format(
                    offset))
        if offset < 0:
            raise ValueError(
                "offset must be a non-negative integer (got {!r})".format(
                    offset))

View on GitHub (pinned to bc6749cc3b)

Solutions

  1. Open the file with 'rb' mode before passing it to loop.sendfile() or similar APIs.

When it happens

Trigger: Raised when connect_write_pipe/connect_read_pipe is given a file opened in text mode.

Common situations: See trigger scenarios.


AI-assisted analysis of python/cpython@bc6749cc3b (2026-08-14). Data as JSON: /api/errors/7139e8993c4e39b9. Report an issue: GitHub.