What is the os.path.getsize() method in Python?
Overview
The os.path.getsize() method in Python is used to get the size of a file. If the file doesn’t exist at the specified path, this method raises a FileNotFoundError exception.
Syntax
os.path.getsize(filePath)
Parameters
This method accepts the following parameter:
filePath: It is the path of the file. It can be a string or a byte object.
Return value
This method returns an integer value that represents the size of the file in bytes.
Example 1
Let’s look at an example of the os.path.getsize() method in the code snippet below.
main.py
demo.txt
# Import the OS modulefrom os.path import getsize# File pathfilePath = 'demo.txt'# Get the file sizefileSize = getsize(filePath)# Print the file sizeprint('File size:', fileSize)
Explanation
- Line 2: We import the **
os**module. - Line 5: We declare a variable
filePathcontaining the file path. - Line 8: We use the
os.path.getsize()method to find the size of the file. - Line 11: We print the size of the file on the console.
Output
- The
os.path.getsize()method gets the size of thedemo.txtfile and prints it on the console.
Example 2
Now, let’s look at an example of the os.path.getsize() method for a non-existing file.
# Import the OS modulefrom os.path import getsize# File pathfilePath = 'demo.txt'# Get the file sizefileSize = getsize(filePath)# Print the file sizeprint('File size:', fileSize)
Output
- If the file is not present at the specified path, this method raises the
FileNotFoundErrorexception. - The same is seen in the above code output.