Python os.path.getsize() Method

Python os.path.getsize() method is “used to check the size of the particular path.” It returns the size of the specified path in bytes. The getsize() method raises OSError if the file does not exist or is somehow inaccessible.

Syntax

os.path.getsize(path)

Parameters

The path-like object parameter represents the file system path. It is a path-like object that is either a string or bytes object representing a path.

Return Value

The os.path.getsize() method returns an integer value representing the specified path’s size in bytes.

Example 1: How to Use os.path.getsize() Method

Define a file path and pass the file path to the getsize() method.

import os

path = "/Users/krunal/Desktop/code/pyt/database/app.py"

size = os.path.getsize(path)

print("The file size in bytes is:", size)

Output

The file size in bytes is: 140

Example 2: OSError

You might get the OSError while using the os.path.getsize() method. To handle the exceptions in Python, use the try-except method.

import os
import sys

path = "/Users/krunal/Desktop/code/pyt/database/data.py"

try:
  size = os.path.getsize(path)

except OSError:
  print("Path '%s' does not exist or inaccessible" % path)
  sys.exit()

print("The file size in bytes is:", size)

Output

Path '/Users/krunal/Desktop/code/pyt/database/data.py' does not exist or inaccessible

You can see that it throws an exception, and we catch the exception and print the statement.

If the path does exist, it will return the size of the file.

import os
import sys

path = "/Users/krunal/Desktop/code/pyt/database/app.py"

try:
  size = os.path.getsize(path)

except OSError:
  print("Path '%s' does not exist or inaccessible" % path)
  sys.exit()

print("The file size in bytes is:", size)

Output

The file size in bytes is: 253

That is it.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.