Python file.read() Method

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

Definition

read() reads from the current position of an open file. With no argument it reads everything that is left; with a number it reads at most that many characters (text mode) or bytes (binary mode).

Each call moves the position forward, so a second read() continues where the first stopped. At the end of the file it returns an empty '' or b'' instead of raising an error.

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

Syntax

Call it on a file opened for reading, optionally with a size limit.

python
data = f.read()
data = f.read(size)
CallWhat it does
f.read()Reads everything from the current position to the end of the file.
f.read(5)Reads at most 5 characters (text mode) or 5 bytes (binary mode).
f.read()At the end of the file: returns '' or b''; no exception.

size is positional only. -1 and None both mean "read to the end". For huge files prefer a loop over lines or fixed-size chunks.

Method signatures
python
TextIOWrapper.read(size=-1, /)    # -> str
BufferedReader.read(size=-1, /)   # -> bytes
FileIO.read(size=-1, /)           # -> bytes, from one system call

Parameters

ParameterDescription
sizeOptional. The maximum number of characters (text mode) or bytes (binary mode) to read. Omitted, -1, or None reads to the end of the file.

Return Value

Return ValueDescription
strIn text mode: the decoded characters. Newlines are already translated to "\n" by default.
bytesIn binary mode: the raw bytes, exactly as stored on disk.
'' / b''When the position is already 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 — Read a Recipe Note in One Call

Write a short note, read it back with one read(), and see what a second call returns.

python
import os
import tempfile

with tempfile.TemporaryDirectory() as folder:
    path = os.path.join(folder, "recipe.txt")
    with open(path, "w", encoding="utf-8") as f:
        f.write("Pancakes\n2 eggs\n1 cup milk\n")

    with open(path, encoding="utf-8") as f:
        text = f.read()
        again = f.read()

    print(repr(text))
    print(len(text), "characters")
    print(text.splitlines()[0])
    print(repr(again))

How It Works

  1. Safe scratch folder. tempfile.TemporaryDirectory() gives a private folder that is deleted, with the recipe inside it, when the block ends.
  2. One call, whole file. f.read() with no size returns all three lines as a single string, newline characters included.
  3. Same text on every OS. Windows stores the line breaks as \r\n, but text mode turns them back into \n, so the count is 27 everywhere.
  4. Nothing left. The position now sits at the end, so the second read() returns an empty string rather than raising.

Example 2 — Process Sensor Bytes in 4-Byte Chunks

Loop with read(4) until it returns empty bytes, the usual pattern for large binary files.

python
import tempfile
from pathlib import Path

with tempfile.TemporaryDirectory() as folder:
    path = Path(folder) / "readings.bin"
    path.write_bytes(bytes(range(10)))

    with open(path, "rb") as f:
        while True:
            chunk = f.read(4)
            if not chunk:
                break
            print(len(chunk), list(chunk))

How It Works

  1. Ten test bytes. bytes(range(10)) stores the values 0 to 9, and Path.write_bytes() saves them in one line.
  2. Bounded reads. Each read(4) returns at most four bytes, so memory use stays small however large the file is.
  3. Short last chunk. Only two bytes remain on the third pass, so read(4) returns just [8, 9].
  4. Empty means done. The fourth call returns b'', which is falsy, and the loop stops.

Example 3 — See read(4) Count Characters vs Bytes

The same UTF-8 file read four units at a time, once in text mode and once in binary mode.

python
import os
import tempfile

with tempfile.TemporaryDirectory() as folder:
    path = os.path.join(folder, "menu.txt")
    with open(path, "w", encoding="utf-8") as f:
        f.write("caf\u00e9 menu\n")

    with open(path, encoding="utf-8") as f:
        word = f.read(4)
    print(len(word), ascii(word))

    with open(path, "rb") as f:
        data = f.read(4)
    print(len(data), data)
    try:
        data.decode("utf-8")
    except UnicodeDecodeError:
        print("4 bytes cut the e-acute in half")

How It Works

  1. Escape keeps the source ASCII. "\u00e9" is the letter e-acute, which UTF-8 stores as the two bytes c3 a9.
  2. Text counts characters. In text mode read(4) returns the whole word café; ascii() prints it with an escape.
  3. Binary counts bytes. In binary mode the same call stops after the first byte of e-acute.
  4. Half a character. Decoding the four bytes fails with UnicodeDecodeError, a reminder to decode complete data or read in text mode.

Frequently Asked Questions

An empty string in text mode or empty bytes in binary mode. It never raises at end of file, so loops test "if not chunk: break".
It depends on the mode. A text file counts characters, which can be several bytes each in UTF-8. A binary file opened with "rb" counts bytes.
The first read() moved the position to the end of the file. Call f.seek(0) to go back to the start, or reopen the file.
Loop over the file object line by line with for line in f, or call read(size) in a loop with a fixed size such as 65536 until it returns empty.
Yes. pathlib.Path(name).read_text(encoding="utf-8") opens, reads, and closes the file in one call; read_bytes() does the same for binary data.

Next: file.readable()

Return True if the stream was opened for reading.

readable() →

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.

15 people found this page helpful