Python | os.truncate () method

Python Methods and Functions

The

OS Module in Python provides functions for interacting with the operating system. The OS comes with standard Python service modules. This module provides a portable way to use operating system specific functionality. 
os.truncate () file corresponding to path so that its size is no longer than bytes. This function can also support file descriptor .

Syntax: os.truncate (path, length)

Parameters:
path: This parameter is the path or file descriptor of the file that is to be truncated.
length: This is the length of the file upto which file is to be truncated.

Return Value: This method does not returns any value.

Example # 1:

Using os.truncate () to truncate a file along its path.

# Python program to explain the os.truncate () method

 
# import of the os module

import os 

  
# path

path = ' C: / Users / Rajnish / Desktop / testfile.txt'

 
# Open the file and get
# the file descriptor associated
# using the os.open () method

fd = os. open (path, os.O_RDWR | os.O_CREAT)

 
# String to write

s = 'Python.Engineering - A Computer Science portal'

 
# Convert string to bytes

line = str . encode (s)

 
# Write line to file
# associated with the file
# descriptor fd
os.write (fd, line )

 
# Using the os.truncate () method
# Using the path as a parameter

os.truncate (path, 10 )

 
# Search the file from the beginning
# using the os.lseek () method

os.lseek (fd, 0 , 0 )

 
# Read file

s = os.read (fd , 15 )

  
# Print line

print (s )

 
# Close the file descriptor
os.close (fd)

Exit:

 b'GeeksforGe' 

Example # 2:
Using os.truncate () to truncating a file using a file descriptor

# Python n Program to explain the os.truncate () method

 
# import the os module

import os 

 
# path

path = ' C: / Users / Rajnish / Desktop / testfile.txt'

 
# Open the file and get
# the file descriptor associated
# using the os.open () method

fd = os. open (path, os.O_RDWR | os.O_CREAT)

 
# String to write

s = 'GeeksforGeeks'

 
# Convert string to bytes

line = str . encode (s)

 
# Write line to file
# associated with file
# fd descriptor
os.write (fd, line)

 
# Using the os.truncate () method
# Using fd as a parameter

os.truncate (fd, 4 )

 
# Search file from the beginning
# using the os.lseek () method

os.lseek (fd, 0 , 0 )

 
# Read file

s = os.read (fd, 15 )

 
# Print line

print (s)

 
# Close the file descriptor
os.close (fd)

Output:

 b'Geek'