0 0
WP Ad Inserter plugin
Read Time:6 Minute, 28 Second

Table of Contents

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:



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

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.close() #open and read the file after the truncate:
f = open("code.txt", "r")

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

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")
CodeFile.close() #file is truncated to 25 byte size
CodeFile = open("code.txt", "a")
CodeFile.close() #reading file after truncation
print("n File contents after truncation :")
CodeFile = open("code.txt", "r")

Example: File Truncation

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")
file_var.close() #It is responsible for reading file contents present inside the file. file_var=open("code.txt","a")
file_var.close() #It is known for truncating the size of the file already created. file_var=open("code.txt","r")
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

Example: Python File truncate() Method

file_var = open("code.txt", "a")
file_var = open("code.txt", "r")

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:


The contents of the file are read by loop as follows:

# -*- 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

Example: interception of 10 bytes codeunderscored.txt file

# -*- 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


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.

Source: https://www.codeunderscored.com/python-file-truncate-method-explained-with-examples/

Two Approaches of Dynamically Generating Images with Azure Functions Previous post Two Approaches of Dynamically Generating Images with Azure Functions
The 10 best vim color schemes for Python, and how to install Next post The 10 best vim color schemes for Python, and how to install

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.