Python file.readinto() Method

Beginner
6 min read
Updated: Nov 2026
3 examples
binary file method

Definition

readinto() reads bytes into a buffer you already own, such as a bytearray, instead of creating a new bytes object. It returns the number of bytes it stored.

Reusing one buffer avoids an allocation per read, which matters in tight loops. Only the first n bytes are new; anything after them is left over from earlier reads.

file.readinto() is a method of the file objects that the built-in open() returns, so no import is needed. It works on binary files (BufferedReader, BufferedWriter, BufferedRandom), and raw files (FileIO, opened with buffering=0).

Syntax

Pass a writable bytes-like object; use the returned count to slice it.

python
buf = bytearray(4096)
n = f.readinto(buf)
chunk = bytes(buf[:n])
CallWhat it does
f.readinto(bytearray(4))Fills up to 4 bytes and returns how many were read.
f.readinto(memoryview(buf)[2:])Fills only part of an existing buffer, without copying.
f.readinto(buf)At the end of the file: returns 0.

The target must be writable: bytes objects are immutable and raise TypeError.

Method signatures
python
BufferedReader.readinto(buffer, /)   # -> int
FileIO.readinto(buffer, /)           # -> int, one system call
io.BytesIO.readinto(buffer, /)       # -> int
# TextIOWrapper has no readinto()

Parameters

ParameterDescription
bufferA writable bytes-like object: bytearray, a memoryview of one, or an array.array. Its length is the maximum read.

Return Value

Return ValueDescription
intHow many bytes were written into the buffer, from 1 to len(buffer).
0End of file. The buffer is left unchanged.

Python Examples

Each example works inside a temporary folder that is deleted at the end, so nothing is left on your disk.

Example 1 — Reuse One 4-Byte Buffer for a Whole File

Read ten letters four at a time into the same bytearray and look at the leftovers.

python
import os
import tempfile

with tempfile.TemporaryDirectory() as folder:
    path = os.path.join(folder, "letters.bin")
    with open(path, "wb") as f:
        f.write(b"ABCDEFGHIJ")

    buf = bytearray(4)
    with open(path, "rb") as f:
        while True:
            n = f.readinto(buf)
            if n == 0:
                break
            print(n, bytes(buf[:n]))
    print(buf)

How It Works

  1. One allocation. bytearray(4) is created once and refilled on every pass.
  2. Count tells the truth. The third call stores only 2 bytes, and slicing with buf[:n] shows just IJ.
  3. Zero ends the loop. At the end of the file readinto() returns 0 instead of raising.
  4. Stale tail. Printing the whole buffer shows IJGH: the last two bytes are left over from the previous read.

Example 2 — Parse an Image Header with readinto() and memoryview

Read a 6-byte header (width, height, depth) into a buffer and decode it without extra copies.

python
import os
import tempfile

with tempfile.TemporaryDirectory() as folder:
    path = os.path.join(folder, "sprite.img")
    with open(path, "wb") as f:
        f.write(bytes([0x01, 0x40, 0x00, 0xF0, 8, 0]) + b"pixels")

    header = bytearray(6)
    with open(path, "rb") as f:
        n = f.readinto(header)
        rest = f.read()

    view = memoryview(header)
    width = int.from_bytes(view[0:2], "big")
    height = int.from_bytes(view[2:4], "big")
    print(n, width, height, header[4])
    print(rest)

How It Works

  1. Header layout. Bytes 01 40 are the width, 00 F0 the height, then a depth byte and a flags byte.
  2. Exact fill. readinto(header) reports 6 and leaves the position right after the header, so read() returns only the pixel data.
  3. Zero-copy slices. memoryview() slices point into the same buffer, and int.from_bytes turns them into 320 and 240.
  4. Single byte as int. Indexing a bytearray such as header[4] gives the integer 8, not a bytes object.

Example 3 — Use readinto() on a Raw FileIO Object

Open a file without buffering, fill an 8-byte slot from a 5-byte file, and check the text layer.

python
import os
import tempfile

with tempfile.TemporaryDirectory() as folder:
    path = os.path.join(folder, "greeting.dat")
    with open(path, "wb") as f:
        f.write(b"hello")

    slot = bytearray(8)
    with open(path, "rb", buffering=0) as raw:
        print(type(raw).__name__)
        print(raw.readinto(slot), bytes(slot[:5]))
        print(raw.readinto(slot))

    with open(path, encoding="utf-8") as text:
        print(hasattr(text, "readinto"))

How It Works

  1. No buffer layer. buffering=0 returns the raw FileIO object, which reads straight from the operating system.
  2. Partial fill. The slot has room for 8 bytes but the file holds 5, so readinto() returns 5.
  3. End of file is 0. The second call has nothing left to read and returns 0.
  4. Text has none. A text-mode file object has no readinto(), because it deals in characters, not raw bytes.

Frequently Asked Questions

The number of bytes it stored in the buffer. It returns 0 at the end of the file.
readinto() refills a buffer you already have, so a loop does not create a new bytes object on every call. That saves memory churn in hot loops.
No. bytes is immutable, so readinto() raises TypeError. Use a bytearray, a memoryview of a bytearray, or an array.array.
A short read only overwrites the first n bytes. Always slice with the returned count, such as buf[:n].
No. TextIOWrapper has no readinto(). Open the file in binary mode with "rb" to use it.

Next: file.readline()

Read one line, including its newline, or an empty result at end of file.

readline() →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

10 people found this page helpful