Truncate() function of os module in Python

Overview:

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

Example:

# 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.open(filePath, os.O_RDONLY,0o744)

# Read the file contents and print
print(os.read(fd, newFileLength))

Output:

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

 


Copyright 2024 © pythontic.com