How to use Python Truncate to Resize Files

One of the common tasks we have to do with a file, floating variables, or strings is that we have to resize it or truncate it according to our needs. To truncate a file in Python, we have a truncate method. For floating-point values, we have a trunc() method of math library.
But we do not have any direct method to truncate a string. So, we will also learn what alternatives we have to truncate a string.

In layman’s terms, Truncate refers to the removal of unwanted parts of anything. Similarly, Python Truncate refers to the removal of unwanted data from lists, dictionaries, tuples, and other files. This method allows you to save memory while executing the code. In this post, we’ll go through all the syntax and usage of the truncate function.

Syntax of Python Truncate

Python truncate()

It is a built-in function in python used for truncating files.

Python Truncate Parameters

It takes only one parameter ‘size,’ and this parameter is optional. If no value is specified, it takes the value where it is currently on. For example, if we have a file in which it is written -” Hello, this is a file I have created to check the truncate method.” Currently, my pointer is on index 10. Then the truncation process will happen after the 10th index.

math.trunc()

This method is used for removing the decimal part of the number.

Parameters

It contains only one parameter, i.e., the number which we want to truncate. If we pass any non-numerical value, we will get a Type Error.

Using Python Truncate to resize a file

As we already know what is truncate (), what are the parameters, let us know how to truncate a file. If you don’t know how to perform read/write operations in a file, look at the following code, and you will know the basics.

# Whether file 'xyz.txt' exist or not, it will open in write 
# mode. Old text will be deleted and we can write new text in 
# 'w' mode.
file=open("xyz.txt","w")
#Using write() to write something in a file
file.write("Hello this is a file which I have created to check the truncate method.")
file.close()
#To read what is written in the file use 'r' mode
file=open("xyz.txt","r")
#read() enable us to read whatever is written in the file
read=file.read()
print(read)
Output-
Hello this is a file which I have created to check the truncate method.
#Now, if we want to add something to this ‘xyz.txt’ we will use ‘a’ (append) #mode.
file=open('xyz.txt','a')
file.write(" This line is being added")
file.close()
file=open("xyz.txt","r")
read=file.read()
file.close()
print(read)
Output-
Hello this is a file which I have created to check the truncate method. This line is being added

Python Truncate Without Parameter

Now let us perform truncate() on ‘xyz.txt’ file.

file1=open('xyz.txt',"w")
file1.write("Hello this is a file which I have created to check the truncate method. This line is being added")
print(file1.truncate())
file1.close()
file1=open('xyz.txt','r')
read=file1.read()
file1.close()
print(read)
Output-
96
Hello this is a file which I have created to check the truncate method. This line is being added

We have just written some text on this file, that is why the pointer is at the last index, so nothing will get deleted. But if we are at the 0th index, everything would have been deleted. We can use the seek() method to go to the 0th index.

file1=open('xyz.txt',"w")
file1.write("Hello this is a file which I have created to check the truncate method. This line is being added")
#seek method moves the pointer to the desired index
file1.seek(5)
print(file1.truncate())
file1.close()
file1=open('xyz.txt','r')
read=file1.read()
file1.close()
print(read)
Output-
5
Hello

Python Truncate With Parameter

If we give some value to the size parameter it will truncate(clear) everything after that index.
In other words, our file we of the size in bytes we have mentioned in the parameter.

file1=open('xyz.txt',"w")
file1.write("Hello this is a file which I have created to check the truncate method. This line is being added")
print(file1.truncate(20))
file1.close()
file1=open('xyz.txt','r')
read=file1.read()
file1.close()
print(read)
Output-
20
Hello this is a file

NOTE- A question may come to your mind, that what if we pass a size greater than the actual size of the file. Well, that totally depends on the IDE we are using.

file1=open('xyz.txt',"w")
file1.write("Hello this is a file which I have created to check the truncate method. This line is being added")
print(file1.truncate(2000))
file1.close()
file1=open('xyz.txt','r')
read=file1.read()
file1.close()
print(read)
Output-
2000
Hello this is a file which I have created to check the truncate method. This line is being added

Here we have specified the size that is greater than the size of our file. When I run this code on Jupyter Notebook, a file like this is created-

python truncate

When I run this code on PyCharm IDE, there is no change.

python truncate

Truncating Floating point values in Python

In Python, to truncate a floating value or in laymen’s terms to remove the value after the decimal, we use the trunc() method of the math library to remove the decimal values. For that, we have to import the math library.

import math
number=3.141592653589793238
math.trunc(number)
Output-
3

Some people get confused that this function is similar to round(). But that is not the case, if we pass a value like 3.99, it will return 3, while round() would have returned 4.

import math
number=3.99
math.trunc(number)
Output-
3

Similarly, if we pass any negative value, it will remove the decimal number and return the output as an integer.

import math
number=-7827812.18219228
math.trunc(number)
Output-
-7827812

Truncating a string in Python

There is no pre-defined method to truncate a string; instead of that, we can use the concept of slicing to achieve the same goal.

If we want to remove everything after the 19t,h index in the string s,’ let us see how we will do it.

s = "Hello this is a file which I have created to check the truncate method. This line is being added."
s=s[:19]
print(s)
Output-
Hello this is a fil

Must Read

Conclusion

We have learned all the techniques to resize a file, floating value, and a string using different python truncate techniques. We have also learned how to create a file and perform read/write operations on it.

Try to run the programs on your side and let me know if you have any queries.

Happy Coding!

Subscribe
Notify of
guest
6 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
jayashri sathe
jayashri sathe
3 months ago

How to truncate pdf/xlsx/docx files using it? I just want same file operation for pdf/xlsx/docx as you did for txt file, please help..

Pratik Kinage
Admin
Pratik Kinage
3 months ago
Reply to  jayashri sathe

You can read the docx and pdf by using modules like docx and PyPDF2. Read and extract the text, then save it as a text file, and then perform the truncate method on your text file.

Regards,
Pratik

jayashri sathe
jayashri sathe
3 months ago
Reply to  Pratik Kinage

But I want .docx file and that should open in word.

I tried to truncate docx file but I am unable to open it in word and able to open it in notepad++, that is the issue I am facing

Pratik Kinage
Admin
Pratik Kinage
3 months ago
Reply to  jayashri sathe

Hi,

Yes, first extract the text from docx and then truncate it. Then save the text back to docx file by using the following code –

from docx import Document
document = Document()
document.add_heading('This is the heading', level=1)
document.add_paragraph('text')
document.save('docx_file.docx')

Make sure you install the docx module first.

Regards,
Pratik

jayashri sathe
jayashri sathe
3 months ago
Reply to  Pratik Kinage

The reason I am using truncate is want fix size of .docx file. It doesn’t matter what data is present in that file.

But the issue I am facing is I am able create and truncate it successfully but unable to open it in word (notepad and word pad open it properly).

Thanks
Jayashree

Pratik Kinage
Admin
Pratik Kinage
3 months ago
Reply to  jayashri sathe

Although, I’m not sure what might be happening in your case. The most probably guess is that you are destroying the docx format while truncating it. Since docx file has a predefined format, the truncate function won’t work on it directly without converting it to text.

Regards,
Pratik