truncate() function of os module in Python

Given a file path the os.truncate() function truncates the file contents of a file to the specified length.

Os Updated 4 May 2023 1 min read

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

python
# 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

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