Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
What is Truncation in Python
3.
File Objects in Python
3.1.
Open
3.2.
Read
3.3.
Write 
4.
Code
4.1.
Example 
4.2.
Output
4.3.
Explanation
5.
File Truncation Example 
6.
Frequently Asked Questions
6.1.
Define the Python truncate function.
6.2.
What are the functions for reading a file in Python?
6.3.
Does the Python truncate function have a return value?
6.4.
What if the size given is greater than the file's current size?
6.5.
What are the different file opening modes in Python?
7.
Conclusion
Last Updated: Mar 27, 2024
Medium

Truncation in Python

Author Ayushi Goyal
0 upvote
gp-icon
Basics of python
Free guided path
7 chapters
99+ problems
gp-badge
Earn badges and level up

Introduction

Python is a high-tech programming language with built-in functions and hence easy to learn for beginners. In this article, we will be discussing about one of the built-in functions, i.e., the Python truncate function. We will be starting with the introduction of the truncate function, followed by the prerequisites and its implementation. 

Introduction

So, let's start with the topic with an introduction to Python truncate function. 

Also read about, Divmod in Python, and Convert String to List Python

What is Truncation in Python

The word 'TRUNCATE' means to shorten something by a given size. The same job is done by the truncate function; it is used to shorten the length of a given file. Size is considered an optional parameter and referred to as the number of bytes upto which the file needs to be truncated. The syntax of the truncate function is as follows:

Syntax of truncate

If the size is specified, then the file will be truncated almost to that size; otherwise, the size is set to the file's current position. If the size given is greater than the current size, the result depends on the platform; the file's size may remain unchanged or increase to the given size. 

As there is no return value of the Python truncate function, you can check the file size in the file properties. You need to right-click on the given file and click on the properties option as shown in the below image. 

file properties

Also see, Merge Sort Python

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

File Objects in Python

The truncate function works on files; hence, it is a prerequisite to be familiar with file objects. The file objects allow us to access and manipulate files using various methods and attributes. Using these objects, we can read and write any number of files. Let's discuss some of the primary file methods required during truncation in Python. 

Open

The open function in Python is used to open stored files. It returns a file object containing the file content. The syntax for this function is as follows:

Syntax of open function

The argument 'mode' is used to specify the mode of the file to be opened. The open function has six different modes. These are:

Modes

Use

"r"

To open the file in read-only mode. If no other mode is specified, it is passed as the default mode. It returns an error if the file does not exist.

"w"

To open the file in writing mode. If the specified file does not exist, this mode creates a new file for you.

"a"

To open the file for adding content to an already existing file. If the specified file does not exist, this mode creates a new file for you.

"x"

This mode is used to create a new file with a specified name.

"b"

This mode handles image files and opens the file in binary mode. 

"t"

By default, text mode is used by the open function. This mode is used to open the specified file in text mode.

 

Also read,python filename extensions

Read

Python provides three built-in methods for reading the data of a file. These are:

  • Read (n) = It is used to read the entire file. If the value of 'N' is specified, it reads only 'N' bytes from the file. 
     
  • Readline (n) = It is used to read only one line. Only 'N' bytes will be read if ' N' is given, but not more than a line. 

Readline conditions

  • Readlines() = It is used to read all the lines and return each as a list of strings. 

Write 

Similar to the read function, Python provides built-in methods for writing over the file. There are two ways to write on a file. These are:

  • Write (string) = This function inserts the string as a single line in the specified file. 
     
  • Writelines(Lines) where Lines = [string1, string2, string3, ....] = It is used to insert a list of multiple strings at the same time in the given file.

Code

Let's see an example of open, read and write functions:

Example 

# Python program to write in a file

# Open a file in read mode
fileObject = open('file.txt', 'r')
print("Before writing file contain : ")
print(fileObject.read())
fileObject.close()

# Open the file in write mode
fileObject = open('file.txt', 'w')

#Define lines and string to be written
str = "Coding Ninjas\n"
lines = ["This is text1 \n", "This is text2 \n", "This is text3 \n"]

# Working of write(string) function
fileObject.write(str)

# Working of writelines(lines) function
fileObject.writelines(lines)
fileObject.close()

# Check the file after writing
fileObject = open('file.txt','r')
print("\nAfter writing the file contain : ")
print(fileObject.read())
fileObject.close()

Output

Output of open, read and write

You can practice by yourself with the help of online python compiler.

Explanation

We have created a new file inside a new folder on the desktop. The file contains the text “This is a new file”. 

We opened the file in read mode and read the file’s content. Now close the file and open it again in write mode. 

We created a string and a list of strings. Write this string and a list of strings to the file using the write function. As the write function overwrites the existing content. So now the file contains only a string and a list of strings. 

Now close the file and open it in read mode. Read the file content after writing and print the result. 

Check out this article - Quicksort Python

File Truncation Example 

We are now familiar with the primary functions required in the Python truncate function. Let's now see an example for clear understanding. 

  • Create a new file, 'file.txt' in a new folder on your desktop. 
  • Right-click on the file.
  • Click the Properties option to see the current file size. 
  • The result will be as follows:
File size before truncate
  • Initially, the file contains 
File content before truncate
  • As the size of our file is 100 bytes. Let's truncate it to 50 Bytes. To do so, run the following code:
# Program to use truncate function

# Open a file
fileObject = open('file.txt', 'w')

# Truncate the file
fileObject.truncate(50)

# Closing the file
fileObject.close()
  • After running the above code, go to the properties option and see the file size. 
File size after truncate
  • And here we go!!!!. Now the size of our file is 50 Bytes. After truncation, the file will become empty.
File after truncate

Also See, Python Round Function.

Frequently Asked Questions

Define the Python truncate function.

The Python truncate function is used to resize the given file to the given number of bytes.

What are the functions for reading a file in Python?

Python provides three built-in functions for reading the file data. These are read(), readline(), and readlines(). 

Does the Python truncate function have a return value?

The truncate() function does not have a return type. We can check the file size from the file properties option to check the result. 

What if the size given is greater than the file's current size?

If the size specified is greater than the file's current size, then the result is platform-dependent. The file size may remain unchanged or increase to the given size. 

What are the different file opening modes in Python?

The open function in Python enables us to use six different file-opening modes. These are read(r), write(w), append(a), binary(b), text(t) and create(x). 

Conclusion

We have briefly discussed the Truncation in Python and different file objects in Python. We also discussed the different file objects, an example of the Python truncate function, and its explanation. We hope that we have helped you achieve a better grip on the topic.

If you found this one interesting, explore our other related blogs as well:

Check out the guided paths on Coding Ninjas Website, online coding coursespractice on Coding Ninjas StudioCoding Ninjas Studio Interview BundleCoding Ninjas Studio Interview ExperiencesCoding Ninjas LibraryCoding Ninjas Studio Contests, and Coding Ninjas Studio Test Series for more excellent content. Do upvote our blog to assist other ninjas in their development. 

Keep learning, and Keep Growing!

Happy Coding!

Previous article
How To Get Filename Extensions In Python?
Next article
Objects and Classes in Python
Guided path
Free
gridgp-icon
Basics of python
7 chapters
127+ Problems
gp-badge
Earn badges and level up
Live masterclass