Python Glossary Русский

all Python 3osfunction

os.ftruncate

os — file descriptors

Truncate the file behind a descriptor to a given length.

Syntax

os.ftruncate(fd, length)

It can both shrink and grow a file: growing fills the tail with zero bytes. It does not move the descriptor position, so a later write may land past the new end and leave a hole. For a Python file object f.truncate(n) is handier, as it accounts for buffers.

Examples

import os
fd = os.open('trunc_demo.txt', os.O_RDWR | os.O_CREAT | os.O_TRUNC)
os.write(fd, b'hello')
os.ftruncate(fd, 2)
os.close(fd)
print(os.path.getsize('trunc_demo.txt'))   # → 2
os.remove('trunc_demo.txt')

See also

Common errors

Open in the full glossarydocs.python.orgReport an inaccuracy