Python file.peek() Method

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

Definition

peek() lets you look ahead in a binary file: it returns bytes from the read buffer but leaves the position where it was, so the next read() still returns those same bytes.

The amount it returns is not fixed: it is whatever the buffer holds, filled with one raw read if it was empty. Slice the result, as in f.peek(4)[:4], when you need an exact number.

peek() is a method of binary buffered readers: io.BufferedReader (from open(path, "rb")) and io.BufferedRandom ("r+b"). Text files, BufferedWriter, raw FileIO, and io.BytesIO do not have it. No import is needed.

Syntax

Call it on a file opened with "rb" or "r+b", then slice to the length you need.

python
ahead = f.peek()
first_four = f.peek(4)[:4]
CallWhat it does
f.peek(4)[:4]The next four bytes (fewer near the end), position unchanged.
f.peek()Everything currently buffered from the position on; may be many bytes.
f.peek(1)At the end of the file: returns b''.

The size argument is only a hint: CPython may return more or fewer bytes, but never moves the position.

Method signatures
python
BufferedReader.peek(size=0, /)   # -> bytes, position unchanged
BufferedRandom.peek(size=0, /)   # -> bytes, position unchanged
# documented as peek([size]); the result length may differ from size

Parameters

ParameterDescription
sizeOptional hint for how many bytes you want. The result may be longer or shorter, so slice it yourself.

Return Value

Return ValueDescription
bytesBytes starting at the current position, copied from the buffer. At most one raw read happens, and only if the buffer was empty.
b''At the end of the file.

Python Examples

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

Example 1 — Check a PNG Signature Before Reading

Peek at the first eight bytes, compare them with the PNG signature, then read the file from the start.

python
import os
import tempfile

PNG_SIGNATURE = b"\x89PNG\r\n\x1a\n"

with tempfile.TemporaryDirectory() as folder:
    path = os.path.join(folder, "icon.png")
    with open(path, "wb") as f:
        f.write(PNG_SIGNATURE + b"IHDR")

    with open(path, "rb") as f:
        head = f.peek(8)[:8]
        print(head == PNG_SIGNATURE, f.tell())
        data = f.read()
        print(len(data), data[:4])

How It Works

  1. Magic number. Real PNG files start with these eight bytes, so a fake 12-byte file with the signature plus IHDR is enough to test.
  2. Exact slice. f.peek(8) may return more than eight bytes; [:8] keeps exactly the signature-sized prefix.
  3. Position untouched. tell() is still 0 after the peek, so nothing was consumed.
  4. Full read afterwards. read() returns all 12 bytes, starting with the very bytes that were peeked.

Example 2 — Detect JSON or CSV from the First Byte

Two price files: decide the format from one peeked byte, then start reading normally.

python
import tempfile
from pathlib import Path

samples = {"prices.json": b'{"tea": 3}', "prices.csv": b"item,price\ntea,3\n"}

with tempfile.TemporaryDirectory() as folder:
    for name, content in samples.items():
        path = Path(folder) / name
        path.write_bytes(content)
        with open(path, "rb") as f:
            first = f.peek(1)[:1]
            kind = "json" if first == b"{" else "csv"
            print(name, "->", kind, f.read(4))

How It Works

  1. Two sample files. The dict maps a file name to its bytes, and Path.write_bytes() creates each file in the temporary folder.
  2. One-byte decision. peek(1)[:1] is a 1-byte bytes object, so it compares cleanly with b"{".
  3. Reader starts fresh. read(4) still begins at byte 0, so a JSON or CSV parser could take over without any seek().
  4. Repr quoting. The JSON bytes contain a double quote, so Python prints them inside single quotes: b'{"te'.

Example 3 — Read Numbers with a Peeking Tokenizer

Collect digits while the next byte is a digit, then let the operator be read normally.

python
import os
import tempfile


def read_number(f):
    digits = b""
    while f.peek(1)[:1].isdigit():
        digits += f.read(1)
    return int(digits)


with tempfile.TemporaryDirectory() as folder:
    path = os.path.join(folder, "sum.txt")
    with open(path, "wb") as f:
        f.write(b"42+7")

    with open(path, "rb") as f:
        left = read_number(f)
        operator = f.read(1)
        right = read_number(f)
        print(left, operator, right)
        print(left + right, f.peek(1)[:1])

How It Works

  1. Look, then take. The loop peeks at the next byte and only calls read(1) when it is a digit, so the + is never swallowed.
  2. Bytes to int. int() accepts the collected b"42" directly and returns 42.
  3. Operator stays available. Because peeking does not consume, f.read(1) returns b'+' next.
  4. Clean stop at the end. After 7, peek(1) returns b''; b''.isdigit() is False, which ends the second number.

Frequently Asked Questions

No. peek() copies bytes from the buffer and leaves the position unchanged, so the next read() returns the same bytes.
peek() returns whatever is in the buffer, which is often a whole block of the file. The size argument is only a hint, so slice the result with [:2].
Yes. Near the end of the file, or when only a few bytes are buffered, the result can be shorter. At the end of the file it is b"".
Not directly: TextIOWrapper has no peek(). Open the file in binary mode with "rb", peek, and decode the bytes yourself.
Checking magic numbers, sniffing a file format, and writing tokenizers that decide what to read next without consuming the byte they inspected.

Next: file.read()

Read the rest of a file, or at most size characters (text) or bytes (binary).

read() →

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.

14 people found this page helpful