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])
Call
What 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
Parameter
Description
buffer
A writable bytes-like object: bytearray, a memoryview of one, or an array.array. Its length is the maximum read.
Return Value
Return Value
Description
int
How many bytes were written into the buffer, from 1 to len(buffer).
0
End 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)
Output
4 b'ABCD'
4 b'EFGH'
2 b'IJ'
bytearray(b'IJGH')
How It Works
One allocation.bytearray(4) is created once and refilled on every pass.
Count tells the truth. The third call stores only 2 bytes, and slicing with buf[:n] shows just IJ.
Zero ends the loop. At the end of the file readinto() returns 0 instead of raising.
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)
Output
6 320 240 8
b'pixels'
How It Works
Header layout. Bytes 01 40 are the width, 00 F0 the height, then a depth byte and a flags byte.
Exact fill.readinto(header) reports 6 and leaves the position right after the header, so read() returns only the pixel data.
Zero-copy slices.memoryview() slices point into the same buffer, and int.from_bytes turns them into 320 and 240.
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"))
Output
FileIO
5 b'hello'
0
False
How It Works
No buffer layer.buffering=0 returns the raw FileIO object, which reads straight from the operating system.
Partial fill. The slot has room for 8 bytes but the file holds 5, so readinto() returns 5.
End of file is 0. The second call has nothing left to read and returns 0.
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.