What is os.truncate() in Python?

The os module

The os module in Python provides functions that help in interacting with the underlying operating system.

The truncate() method

The truncate() method truncates the given file descriptor or the file path with respect to the given length in bytes.

Syntax


truncate(path, length)

Parameters

  • path: This is the file path.
  • length: This is the max length in bytes after truncation.

Return value

This function returns nothing.

Code

import os
f_path = "file.txt"
f_contents = "hello-world\nhello-edpresso"
with open(f_path, "w") as f:
f.write(f_contents)
print("Before truncation contents of the file: ")
f_contents = open(f_path).read()
print(f_contents)
os.truncate(f_path, 10)
print("--" * 5)
f_contents = open(f_path).read()
print("After truncation contents of the file: ")
print(f_contents)

Code explanation

  • Line 1: We import the os module.
  • Line 3: We define a file path called f_path.
  • Line 5: We define the file’s contents called f_contents.
  • Lines 7-8: We write f_contents to the file f_path.
  • Lines 10-12: The contents of the f_path are read. These are then printed to the console before the truncation.
  • Line 14: We truncate the file f_path to 10 bytes using the os.truncate() method. This method modifies the original file.
  • Lines 16-19: The contents of the f_path are re-read. We then print these to the console after the truncation.

Free Resources