Truncate() Function Of Os Module In Python


  • The os.truncate() function removes the contents of a file that is available beyond the specified length. The remaining contents are left untouched.


# Example Python program that truncates a file
# to a specified length using the function
# os.truncate()
import os

# Truncate the file to have only the first two lines
filePath         = "/PythonProgs/Rain.txt"
newFileLength     = 45 # in bytes
os.truncate(filePath, newFileLength)

# Open the truncated file
fd =, os.O_RDONLY,0o744)

# Read the file contents and print
print(, newFileLength))


b'Rain, rain, go away\nCome again some other day'


Copyright 2023 ©