Python Glossary Русский

Python 3.3+osfunction

os.truncate

os — file descriptors

Truncate the file at a path to a given length.

Syntax

os.truncate(path, length)

It takes a path, not a descriptor, so the file need not be opened. Growing fills the tail with zeros, and on filesystems with sparse files no disk space may actually be allocated. On Windows it works since Python 3.5. If the file is already open, os.ftruncate on its descriptor is safer.

Examples

import os
with open('hello.txt', 'wb') as f:
    f.write(b'hello')
os.truncate('hello.txt', 2)
print(os.path.getsize('hello.txt'))   # → 2
os.remove('hello.txt')

See also

Common errors

Open in the full glossarydocs.python.orgReport an inaccuracy