Tuesday, September 24, 2024
Google search engine
HomeLanguagesPython | os.truncate() method

Python | os.truncate() 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.truncate() method truncates the file corresponding to path so that it is at most length bytes in size. This function can support file descriptor too.

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() method to truncate a file using it’s path.




# Python program to explain os.truncate() 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 = 'Lazyroar - A 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.truncate() method
# Using path as parameter
os.truncate(path, 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'

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




# Python program to explain os.truncate() 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 = 'Lazyroar'
  
# 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.truncate() method
# Using fd as parameter
os.truncate(fd, 4)
  
# 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'Geek'

Last Updated :
25 Jun, 2019
Like Article
Save Article

<!–

–>

Similar Reads
Related Tutorials
Dominic Rubhabha-Wardslaus
Dominic Rubhabha-Wardslaushttp://wardslaus.com
infosec,malicious & dos attacks generator, boot rom exploit philanthropist , wild hacker , game developer,
RELATED ARTICLES

Most Popular

Recent Comments