Python file.truncate() Method

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

Definition

truncate() changes the size of an open file. With no argument it cuts the file at the current position; with a number it makes the file exactly that many bytes long.

It returns the new size and does not move the position. The file must be open for writing, for example with "r+", "w+", or "r+b".

file.truncate() 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 with no argument, or with the new size in bytes.

python
new_size = f.truncate()
new_size = f.truncate(size)
CallWhat it does
f.truncate()Cuts everything after the current position.
f.truncate(0)Empties the file; the position stays where it was.
f.truncate(100)Grows a shorter file to 100 bytes, filling with zero bytes.

The size is always in bytes, even for text files. In text mode, cut at a position you got from tell() or at 0.

Method signatures
python
IOBase.truncate(size=None, /)   # -> int, the new size in bytes
# needs write access: "r+", "w", "w+", "a", "a+" (or the "b" versions)

Parameters

ParameterDescription
sizeOptional new size in bytes. None or omitted means "the current position".

Return Value

Return ValueDescription
intThe new size of the file in bytes.

Python Examples

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

Example 1 — Keep Only the First Two Log Lines

Read two lines in "r+b" mode, cut the rest, and try the same on a read-only file.

python
import io
import os
import tempfile

with tempfile.TemporaryDirectory() as folder:
    path = os.path.join(folder, "events.log")
    with open(path, "wb") as f:
        f.write(b"line1\nline2\nline3\n")

    with open(path, "r+b") as f:
        f.readline()
        f.readline()
        print(f.truncate(), f.tell())
        f.seek(0)
        print(f.read())

    with open(path, "rb") as f:
        try:
            f.truncate(0)
        except io.UnsupportedOperation:
            print("read-only file: truncate() not supported")

How It Works

  1. Find the cut point. Two readline() calls leave the position at byte 12, right after line2\n.
  2. Cut there. truncate() with no argument uses that position, returns the new size 12, and leaves tell() at 12.
  3. Check the result. Rewinding with seek(0) and reading shows only the first two lines remain.
  4. Needs write access. On a file opened with "rb", truncation raises io.UnsupportedOperation.

Example 2 — Shrink a File, Then Grow It with Zero Bytes

Use explicit sizes in "w+b" mode and watch the position stay put.

python
import os
import tempfile

with tempfile.TemporaryDirectory() as folder:
    path = os.path.join(folder, "slots.dat")
    with open(path, "w+b") as f:
        f.write(b"0123456789")
        print(f.truncate(4), f.tell())
        f.seek(0)
        print(f.read())
        print(f.truncate(6))
        f.seek(0)
        print(f.read())

How It Works

  1. Explicit size. truncate(4) keeps only the first four bytes and returns 4.
  2. Position untouched. tell() still reports 10, now past the end of the shorter file.
  3. Grow the file. truncate(6) makes the file longer; the two new bytes read back as \x00.

Example 3 — Rewrite a Config File in Place Without Leftovers

Overwrite a longer file with shorter text in "r+" mode, once without and once with truncate().

python
import os
import tempfile


def rewrite(path, new_text, cut):
    with open(path, "r+", encoding="utf-8", newline="\n") as f:
        f.read()
        f.seek(0)
        f.write(new_text)
        if cut:
            f.truncate()
    with open(path, encoding="utf-8", newline="\n") as f:
        return f.read()


with tempfile.TemporaryDirectory() as folder:
    path = os.path.join(folder, "app.cfg")
    for cut in (False, True):
        with open(path, "w", encoding="utf-8", newline="\n") as f:
            f.write("mode=verbose\nlevel=10\n")
        print(cut, repr(rewrite(path, "mode=quiet\n", cut)))

How It Works

  1. Overwrite, not replace. Writing 11 characters at position 0 only replaces the first 11 bytes of the 22-byte file.
  2. Leftover garbage. Without truncation the old tail e\nlevel=10\n survives, producing a broken config.
  3. Cut after writing. truncate() at the position after the new text removes everything that followed.
  4. Predictable offsets. newline="\n" keeps one byte per line ending, so the leftover is the same on Windows and Linux.

Frequently Asked Questions

Open it with "w", which empties it immediately, or call f.truncate(0) on a file opened with "r+" and then seek(0) before writing.
No. It returns the new size but leaves the position unchanged, even if that position is now past the end of the file.
The new size of the file in bytes.
Yes. Passing a size larger than the file extends it; on common file systems the added bytes read back as zeros.
The file was opened without write access, such as with "r" or "rb". Open it with "r+" or "r+b" instead.

Next: file.writable()

Return True if the stream was opened for writing.

writable() →

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.

9 people found this page helpful