Python | os.truncate() method
Last Updated :
16 Jan, 2024
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
import os
path = 'C:/Users/Rajnish/Desktop/testfile.txt'
fd = os. open (path, os.O_RDWR | os.O_CREAT)
s = 'GeeksforGeeks - A Computer Science portal'
line = str .encode(s)
os.write(fd, line)
os.truncate(path, 10 )
os.lseek(fd, 0 , 0 )
s = os.read(fd, 15 )
print (s)
os.close(fd)
|
Output:
b'GeeksforGe'
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 ‘GeeksforGeeks‘ 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 = 'C:/Users/Rajnish/Desktop/testfile.txt'
fd = os. open (path, os.O_RDWR | os.O_CREAT)
s = 'GeeksforGeeks'
line = str .encode(s)
os.write(fd, line)
os.truncate(fd, 4 )
os.lseek(fd, 0 , 0 )
s = os.read(fd, 15 )
print (s)
os.close(fd)
|
Output:
b'Geek'
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...