File Truncate() Method In Python

In this tutorial, we will learn file truncate() method in Python with an example.

File truncate() is a very efficient method. First of all, it is called a method because it includes the file name(i.e. object of file) and a dot operator and not a function because it is not called directly by name it includes some other factors too(i.e. object of file).

Truncation simply means cutting-off something. Here, our sense of cutting-off is in terms of size.

It is similar to a mathematical function in Python itself in which the numbers present after the decimal pint is truncated from a whole number present.

File truncate() Method

Basically, it contains 3 things:-

1. Syntax:-

fileobject.truncate([size])

Here, a file object is the object which we create while opening a file.

2. Parameters:-
It is not necessary to send the parameter.
The size if specified as a parameter then it should be in bytes.

3. Return Value:-
It does not write anything as it works in terms of the size of the file.
(In IDLE where you run one line after the other -,there while running this statement it shows the number of bites truncated.)

**It does not work when the file is in the read mode.

If the size is specified then it truncates to (at most) that size and if not then to the current position where the current position remains unchanged.
If the specified truncation size exceeds the current size of the file then the result or output will be platform dependent.
There may be various possibilities for that some are:-

  • The file size does not change at all.
  • The file size increases to the specified truncation size with no contents at all i.e. zero-filled.
  • The file size increases to the specified truncation size with some unknown contents in it.

CODE

file=open("truncate.txt","a")
file.write("Hey Everyone... Here you will come to know about a very important python method which is  File truncate(). So, let's begin...") 
file.close()

#It first creates a file named "truncate" and add the contents in that file.

file=open("truncate.txt","r")
print(file.read())
file.close()

#It reads the contents present inside the file.

file=open("truncate.txt","a")
file.truncate(25)
file.close()

#It truncates the size of the already created file.

file=open("truncate.txt","r")
print(file.read())
file.close()

#Here, we can see what all changes are made in the contents of the file after truncating the isze of the file.

#This method can be applied simply also if you already have a file created and you know what all contents and properties (size) it haves . For better understanding i have made a long code.

OUTPUT

Hey Everyone... Here you will come to know about a very important python method which is File truncate(). So, let's begin...
Hey Everyone... Here you

Also read:

Leave a Reply

Your email address will not be published. Required fields are marked *