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.
os.path.getsize(filePath)
This method accepts the following parameter:
filePath
: It is the path of the file. It can be a string or a byte object.This method returns an integer
value that represents the size of the file in bytes.
Let’s look at an example of the os.path.getsize()
method in the code snippet below.
# 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)
os**
module.filePath
containing the file path.os.path.getsize()
method to find the size of the file.os.path.getsize()
method gets the size of the demo.txt
file and prints it on the console.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)
FileNotFoundError
exception.