all Python 3Files & I/Ofunction
io.IOBase.truncate()
resizing
Truncates the file to the given size in bytes. With no size it truncates at the current cursor position. The file has to be open for writing.
Syntax
file.truncate(size=None)
The classic trap: truncate() does not move the file position. Open in 'r+', read the whole file, call f.truncate(0) and write immediately, and the write starts at the old offset with the gap padded by null bytes — you need f.seek(0) first. If size is larger than the current length, the file is extended with zero bytes instead of raising.
Examples
import os
with open('data.txt', 'w') as f:
f.write('много текста')
# очистить файл
with open('data.txt', 'r+') as f:
f.truncate(0)
print(os.path.getsize('data.txt')) # → 0
import os
# обрезать до 100 байт
with open('big.bin', 'wb') as f:
f.write(bytes(1000))
with open('big.bin', 'r+b') as f:
f.truncate(100)
print(os.path.getsize('big.bin')) # → 100
See also
Open in the full glossarydocs.python.orgReport an inaccuracy