Python | os.truncate() method
os.truncate()
method truncates the file corresponding to the path so that it is at the most length bytes in size. This function can support file descriptors too. In this article, we will learn about Python os.truncate() method.
os.truncate() Method Syntax in Python
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.
Python os.truncate() Method Example
Below are some examples by which we can see Python file truncate and Python truncate file using Python os.truncate() in OS module:
Truncate a File Path in Python Using os.truncate()
Method
In this example, the code opens a file at the specified path, writes a string to it, truncates the file to the first 10 bytes, seeks to the beginning of the file, reads the first 15 bytes, and finally prints the read content.
Note: The code may not work as intended because the file descriptor (`fd`) is used with both os.write() and os.read(), and there is no explicit flushing between the write and read operations.
Python3
# importing os module import os # path path = 'C:/Users/Rajnish/Desktop/testfile.txt' # Open the file fd = os. open (path, os.O_RDWR | os.O_CREAT) # String to be written s = 'w3wiki - A Computer Science portal' # Convert the string to bytes line = str .encode(s) # Write the bytestring to the file os.write(fd, line) os.truncate(path, 10 ) # 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'BeginnerforGe'
Truncate a File Using a File Descriptor and os.truncate() Method
In this example, the Python program uses the os.truncate() method to truncate a file (`testfile.txt`) to a specified size (4 bytes). It first writes the string ‘w3wiki‘ to the file, then truncates it to 4 bytes using the file descriptor obtained through os.open(), and finally reads and prints the content of the truncated file.
Python3
import os # path path = 'C:/Users/Rajnish/Desktop/testfile.txt' # Open the file fd = os. open (path, os.O_RDWR | os.O_CREAT) # String to be written s = 'w3wiki' # Convert the string to bytes line = str .encode(s) os.write(fd, line) # Using fd as parameter os.truncate(fd, 4 ) # 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'