AppDividend
Latest Code Tutorials

Python os.path.getsize() Function with Example

0

Python provides an inbuilt OS module that can be used for interacting with the operating system. The os.path module is a submodule of the OS module used for common path name manipulation.

Python os.path.getsize()

To get the file size in bytes in Python, use the os. path.getsize() function. The 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 os.path.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 representing 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 that represents the size of the specified path in bytes.

Example

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

You can see that the file size for the python file is 140 bytes.

Handling OSError in Python

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 then, 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 for Python os.path.getsize() method.

See also

Python os.path.isfile()

Python os.path.split()

Python os.path.dirname()

Python os.path.abspath()

Python os.path.basename()

Leave A Reply

Your email address will not be published.

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