Wednesday, July 3, 2024
HomeLanguagesPythonPython | os.ftruncate() method

Python | os.ftruncate() method

OS module in Python provides functions for interacting with the operating system. OS comes under Python’s standard utility modules. This module provides a portable way of using operating system dependent functionality.
os.ftruncate() method truncates the file corresponding to file descriptor fd, so that it is at most length bytes in size.

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() method to truncate a file




# Python program to explain os.ftruncate() method 
        
# importing os module 
import os 
    
# path 
path = 'C:/Users/Rajnish/Desktop/testfile.txt'
  
# Open the file and get
# the file descriptor associated
# with it using os.open() method
fd = os.open(path, os.O_RDWR|os.O_CREAT)
  
# String to be written
s = 'neveropen'
  
# Convert the string to bytes 
line = str.encode(s)
  
# Write the bytestring to the file 
# associated with the file 
# descriptor fd 
os.write(fd, line)
  
# Using os.ftruncate() method
os.ftruncate(fd, 5)
  
# Seek the file from beginning
# using os.lseek() method
os.lseek(fd, 0, 0)
  
# Read the file
s = os.read(fd, 15)
  
# Print string
print(s)
  
# Close the file descriptor 
os.close(fd)


Output:

b'Geeks'

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




# Python program to explain os.ftruncate() method 
        
# importing os module 
import os 
    
# path 
path = 'C:/Users/Rajnish/Desktop/testfile.txt'
  
# Open the file and get
# the file descriptor associated
# with it using os.open() method
fd = os.open(path, os.O_RDWR|os.O_CREAT)
  
# String to be written
s = 'neveropen - Computer Science portal'
  
# Convert the string to bytes 
line = str.encode(s)
  
# Write the bytestring to the file 
# associated with the file 
# descriptor fd 
os.write(fd, line)
  
# Using os.ftruncate() method
os.ftruncate(fd, 10)
  
# Seek the file from beginning
# using os.lseek() method
os.lseek(fd, 0, 0)
  
# Read the file
s = os.read(fd, 15)
  
# Print string
print(s)
  
# Close the file descriptor 
os.close(fd)


Output:

b'GeeksforGe'

Last Updated :
25 Jun, 2019
Like Article
Save Article

<!–

–>

Similar Reads
Related Tutorials
Thapelo Manthata
I’m a desktop support specialist transitioning into a SharePoint developer role by day and Software Engineering student by night. My superpowers include customer service, coding, the Microsoft office 365 suite including SharePoint and power platform.
RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments