The truncate() technique reduces the size of a file. If the optional size parameter is given, the file is truncated to (at most) that size. The size is set to the current location by default. In addition, there is no change to the current file position.
The method of truncating a file is incredibly efficient. To begin with, it is referred to as a method because it includes the file name (i.e., the object of the file) and a dot operator rather than a function because it is not called directly by name and involves other factors (i.e., object of file).
Note that if a provided size is more than the file’s size, the outcome is platform-dependent: the file may remain unmodified, grow to the supplied size as if zero-filled, or grow to the specified size with undefined new content.
Python File Truncate method
Truncation means to cut something off. Our perception of cutting-off is in terms of size in this case. It’s similar to a mathematical function in Python that truncates the values following the decimal point to the nearest whole number. You can truncate a file by opening it in append or write mode.
The syntax is as follows:
fileObject.truncate(size)
The size parameter is Optional. And it refers to the file’s size after the truncation (in bytes). By default, it is None, which denotes the current location of the file stream. If the size is supplied, it truncates to (at most) that size; otherwise, it truncates to the current position, which remains unaffected. The outcome or output will be platform-dependent if the requested truncation size exceeds the current file size.
This could be a result of many factors, including:-
- The file size remains unchanged.
- The file size grows to the chosen truncation size with no contents, i.e., zero-filled.
- The file size grows to the chosen termination size with some unknown contents.
Let’s make the file 100 bytes in size.
# Python program to demonstrate # truncate() method fp = open('code.txt', 'w') # Truncates the file to specified # size fp.truncate(100) # Closing files fp.close()
Using with statement
In the methods described above, the file must be explicitly closed each time opened. Many changes in files do not take effect until the file is correctly closed. Therefore if one forgets to shut the file, it may introduce various flaws in the code. You can avoid this by using a with the statement.
In Python, the with statement is used in exception handling to make the code clearer and easier to comprehend. It makes it easier to manage common resources such as file streams. Take a look at the following code to see how the use of the with statement makes the code cleaner.
It is not necessary to call a file. When utilizing the ‘with the statement’, use close(). The with statement guarantees that resources are acquired and released correctly.
# Python program to demonstrate # truncate method using with the statement with open('code.txt', 'w') as fp: fp.truncate(50)
Example: Python File truncate() Method
f = open("code.txt", "a") f.truncate(20) f.close() #open and read the file after the truncate: f = open("code.txt", "r") print(f.read())
Example: usage of truncate() method
#!/usr/bin/python # Open a file file_var = open("code.txt", "rw+") print "Name of the file: ", file_var.name # Assuming the file has the following 5 lines # This is 1st line # This is 2nd line # This is 3rd line # This is 4th line # This is the 5th line line_var = file_var.readline() print "Read Line: %s" % (line_var) # Now truncate remaining file. file_var.truncate() # Try to read file now line_var = file_var.readline() print "Read Line: %s" % (line_var) # Close opend file file_var.close()
Example: truncate a file in Python
Assume we have a text file called code.txt. The following is a list of the contents of this file:
This code.txt file is a test file. The contents herein are to demonstrate how file truncation occurs in Python.
#reading file before truncation print("Before truncation file contains:") CodeFile = open("code.txt", "r") print(CodeFile.read()) CodeFile.close() #file is truncated to 25 byte size CodeFile = open("code.txt", "a") CodeFile.truncate(25) CodeFile.close() #reading file after truncation print("\n File contents after truncation :") CodeFile = open("code.txt", "r") print(CodeFile.read()) CodeFile.close()
Example: File Truncation
file_var=open("code.txt","a") file_var.write("Hello there, everyone...File truncate is a required python method that you will learn about here.So, let's get started... ") file_var.close() #It first creates a file named "truncate" and adds the contents in that file. file_var=open("code.txt","r") print(file_var.read()) file_var.close() #It is responsible for reading file contents present inside the file. file_var=open("code.txt","a") file_var.truncate(25) file_var.close() #It is known for truncating the size of the file already created. file_var=open("code.txt","r") print(file_var.read()) file_var.close() #After truncating the file's size, we can check what modifications have been made to the file's contents. #If you already have a file and know what it contains and what properties (size) it has, this method may # be used quickly. We've written an extended code to help you understand.
Example: Python File truncate() Method with Example
# file creation file_var = open("code.txt", "w") # writing text to the file file_var.write("Python is a high-level, interpreted programming language that is used for a variety of tasks. ") # file truncation file_var.truncate(23) #finally, close the file file_var.close() # reading the text from the file and printed it file_var = open("code.txt", "r") print(file_var.read()) # closing the file file_var.close()
Example: Python File truncate() Method
file_var = open("code.txt", "a") file_var.truncate(25) file_var.close() file_var = open("code.txt", "r") print(file_var.read())
Example: Using a loop to demonstrate the truncate () method
The truncate() method is demonstrated in the following example. First, the following is the content file for codeunderscored.txt:
1:www.codeunderscored.com 2:www.codeunderscored.com 3:www.codeunderscored.com 4:www.codeunderscored.com 5:www.codeunderscored.com
The contents of the file are read by loop as follows:
#!/usr/bin/python # -*- coding: UTF-8 -*- # open a file file_var = open("codeunderscored.txt", "r+") print("filename: ", file_var.name) line_var = file_var.readline() print("read first line: %s" % (line_var)) # Truncate the remaining string file_var.truncate() # try to read the data again line_var = file_var.readline() print("Read data: %s" % (line_var)) # close file file_var.close()
Example: interception of 10 bytes codeunderscored.txt file
#!/usr/bin/python # -*- coding: UTF-8 -*- # open a file file_var = open("codeunderscored.txt", "r+") print "File name:", file_var.name # truncate 10 bytes file_var.truncate(10) str_var = file_var.read() print "Read data: %s" % (str_var) # close file file_var.close()
Conclusion
The truncate() method reduces the size of a file to the number of bytes specified. The current position is utilized if the size is not supplied.
If the optional size parameter is given, the file is truncated to (at most) that size. The size is set to the current location by default. Also, there is no change to the current file position. The result is platform-dependent if the provided size exceeds the file’s current size. Note that if the file is opened in read-only mode, this approach will not function.