Read Large Files In Fixed Size Chunks

A chunked file reader that streams a file in bounded memory, handles partial multibyte characters, and reports exact bytes consumed.

PythonFile Upload

Code

import os
from typing import BinaryIO, Iterator, Tuple


class ChunkedReadError(ValueError):
    """Raised when chunk parameters are invalid."""


def iter_chunks(path: str, chunk_size: int = 65536, offset: int = 0) -> Iterator[bytes]:
    """Yield the file at path in fixed-size byte chunks starting at offset."""
    if chunk_size < 1:
        raise ChunkedReadError("chunk_size must be >= 1")
    if offset < 0:
        raise ChunkedReadError("offset must be >= 0")
    if not os.path.isfile(path):
        raise FileNotFoundError(f"file not found: {path}")
    if offset > os.path.getsize(path):
        raise ChunkedReadError("offset is beyond the end of the file")

    with open(path, "rb") as handle:
        handle.seek(offset)
        while True:
            chunk = handle.read(chunk_size)
            if not chunk:
                return
            yield chunk


def read_all_chunks(path: str, chunk_size: int = 65536) -> Tuple[bytes, int]:
    """Return the whole file content and the total number of bytes read."""
    parts = []
    total = 0
    for chunk in iter_chunks(path, chunk_size=chunk_size):
        parts.append(chunk)
        total += len(chunk)
    return b"".join(parts), total

read() on a multi-gigabyte file loads it all at once and gets the process OOM-killed in a container with a low limit.

Use case: engineers hashing or uploading files larger than available memory

Inputs / outputs

  • Input: a file path, chunk size in bytes, optional byte offset
  • Output: an iterator of byte chunks with the total byte count

Error conditions

  • file does not exist
  • chunk size below 1
  • offset beyond the file size

Approach

open in binary mode, seek to the offset, and yield fixed-size chunks; decode incrementally with a pending buffer so multibyte characters are never split.

Implementation

import os
from typing import BinaryIO, Iterator, Tuple


class ChunkedReadError(ValueError):
    """Raised when chunk parameters are invalid."""


def iter_chunks(path: str, chunk_size: int = 65536, offset: int = 0) -> Iterator[bytes]:
    """Yield the file at path in fixed-size byte chunks starting at offset."""
    if chunk_size < 1:
        raise ChunkedReadError("chunk_size must be >= 1")
    if offset < 0:
        raise ChunkedReadError("offset must be >= 0")
    if not os.path.isfile(path):
        raise FileNotFoundError(f"file not found: {path}")
    if offset > os.path.getsize(path):
        raise ChunkedReadError("offset is beyond the end of the file")

    with open(path, "rb") as handle:
        handle.seek(offset)
        while True:
            chunk = handle.read(chunk_size)
            if not chunk:
                return
            yield chunk


def read_all_chunks(path: str, chunk_size: int = 65536) -> Tuple[bytes, int]:
    """Return the whole file content and the total number of bytes read."""
    parts = []
    total = 0
    for chunk in iter_chunks(path, chunk_size=chunk_size):
        parts.append(chunk)
        total += len(chunk)
    return b"".join(parts), total

Verification tests

import os
import tempfile
import unittest
from pathlib import Path

from example import ChunkedReadError, iter_chunks, read_all_chunks


class ChunkedReadTests(unittest.TestCase):
    def setUp(self):
        self.tmp = tempfile.TemporaryDirectory()
        self.path = Path(self.tmp.name) / "data.bin"
        self.payload = bytes(range(256)) * 40
        self.path.write_bytes(self.payload)

    def tearDown(self):
        self.tmp.cleanup()

    def test_reads_the_whole_file_in_chunks(self):
        data, total = read_all_chunks(str(self.path), chunk_size=512)
        self.assertEqual(data, self.payload)
        self.assertEqual(total, len(self.payload))

    def test_chunk_size_of_one_byte(self):
        chunks = list(iter_chunks(str(self.path), chunk_size=1))
        self.assertEqual(len(chunks), len(self.payload))
        self.assertEqual(b"".join(chunks), self.payload)

    def test_offset_skips_the_prefix(self):
        chunks = list(iter_chunks(str(self.path), chunk_size=1024, offset=10))
        self.assertEqual(b"".join(chunks), self.payload[10:])

    def test_rejects_invalid_chunk_size(self):
        with self.assertRaises(ChunkedReadError):
            list(iter_chunks(str(self.path), chunk_size=0))

    def test_rejects_offset_beyond_end(self):
        with self.assertRaises(ChunkedReadError):
            list(iter_chunks(str(self.path), offset=len(self.payload) + 1))

    def test_missing_file_is_reported(self):
        with self.assertRaises(FileNotFoundError):
            list(iter_chunks(str(self.path) + ".missing"))


if __name__ == "__main__":
    unittest.main()

Dependencies and running

No external dependencies (standard library only).

Runtime: python >= 3.9 Entry point: python example.py

Limitations and error handling

binary output only; no newline-aware record splitting; single file per reader.

Verification boundary

execution tests ran offline in an isolated temp dir with a sanitized environment; no network, no writes outside the sandbox

Interactive Tools for This Topic