Getting the size of a text file is a frequent task when working with file handling in Python. It is essential to learn how large a file is, especially when dealing with larger files.
Steps:
Step 1: Add sample text to the example.txt and save it
All the world's a stage, And all the men and women merely players; They have their exits and their entrances, And one man in his time plays many parts.
Step 2: Importing OS module
To get the size of a file, we’ll use the “os” module in Python. This module is used for accessing the file system and provides a range of useful functions for accessing and manipulating files.
Step 3: Use the OS path.getsize() method
After importing the os module, we can use the “path.getsize()” method to determine the size of our file. The getsize() method takes a file name as input and returns the size of the file in bytes.
Step 4: Open the file
Before getting the size of the file, we need to open it in Python. We use the “open()” method to open the file, which takes two input parameters: the file name and the mode.
Step 5: Close the file
After reading or writing to the file, close it with the “close()” method.
Step 6: Print the file size
Once we have opened the file and utilized the getsize() method, we can now print out the size of the file.
Full code:
1 2 3 4 5 6 7 8 9 10 11 12 13 |
import os # Opening the file file = open("example.txt", "r") # Getting the size of the file size = os.path.getsize("example.txt") # Closing the file file.close() # Printing the size of the file print("The size of the file is:", size, "bytes") |
Output:
The size of the file is: 154 bytes
Conclusion:
In conclusion, getting the size of a text file in Python is a simple task when using the “os” module. This tutorial has shown you the necessary steps and code to achieve this, and now you can determine the size of your file with ease.