Python | os.ftruncate () 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.ftruncate () the file corresponding to the file descriptor fd , so that it is os.ftruncate () no more than bytes .

Syntax: os.ftruncate (fd, length)

Parameters:
fd: This is the file descriptor 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.ftruncate () to truncate the file

# Python program to explain the os.ftruncate () 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 = 'GeeksforGeeks'

  
# Convert string to bytes

line = str .encode (s)

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

  
# Using the method os.ftruncate ()

os.ftruncate (fd, 5 )

 
# Search file from 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'Geeks' 

Example # 2 :
Using os.ftruncate () to truncate a file

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

  # import of the os module

import os 

 
# path

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

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

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

  
# String to write

s = ' Python.Engineering - Computer Science portal'

 
# Convert string to bytes

line = str .encode (s)

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

  
# Using the method os.ftruncate ()

os.ftruncate (fd, 10 )

 
# Search file from 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' 




Get Solution for free from DataCamp guru