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.
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
Parameter
Description
size
Optional new size in bytes. None or omitted means "the current position".
Return Value
Return Value
Description
int
The 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")
Output
12 12
b'line1\nline2\n'
read-only file: truncate() not supported
How It Works
Find the cut point. Two readline() calls leave the position at byte 12, right after line2\n.
Cut there.truncate() with no argument uses that position, returns the new size 12, and leaves tell() at 12.
Check the result. Rewinding with seek(0) and reading shows only the first two lines remain.
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())
Output
4 10
b'0123'
6
b'0123\x00\x00'
Growing a file with truncate() fills the gap with zero bytes on Linux, macOS, and Windows (NTFS) in practice; the exact behavior is up to the operating system.
How It Works
Explicit size.truncate(4) keeps only the first four bytes and returns 4.
Position untouched.tell() still reports 10, now past the end of the shorter file.
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)))