Python | os.path.size() method (original) (raw)

Last Updated : 15 Jan, 2024

*OS module in Python provides functions for interacting with the operating system. OS comes under Python’s standard utility modules. This module provides a portable way of using operating system-dependent_*the **_ functionality. **os.path module is a submodule of the OS module in Python used for common path name manipulation. In this article, we will discuss how to determine the file size with os.path.getsize() in Python.

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

Python os.path.getsize() method Syntax

**Syntax: _os. path.getsize(path)

**Parameter:

**Return Type: _This method returns a integer value which represents the size of specified path in _bytes.

os.path.getsize() method in Python

Below are the following ways by which we can see how to determine the file size with os.path.getsize() in Python.

Working Withos.path.getsize()Method in Python

In this example, the os.path.getsize() method is used to retrieve and display the size of a file located at the specified path (/home/User/Desktop/file.txt) in bytes.

Python3

import os

path = '/home/User/Desktop/file.txt'

size = os.path.getsize(path)

print ( "Size (In bytes) of '%s':" % path, size)

Output

Size (In bytes) of '/home/User/Desktop/file.txt': 243

Handling Error While Using os.path.getsize() Method in Python

In this example, the script attempts to retrieve the size of a file located at the specified path (/home/User/Desktop/file2.txt). If the file does not exist or is inaccessible, it prints an error message and exits the program.

Python3

import os

path = '/home/User/Desktop/file2.txt'

try :

`` size = os.path.getsize(path)

except OSError:

`` print ( "Path '%s' does not exists or is inaccessible" % path)

`` sys.exit()

print ( "Size (In bytes) of '% s':" % path, size)

Output

Path '/home/User/Desktop/file2.txt' does not exists or is inaccessible

Finding the Sizes of Multiple Files

In this example, the script iterates over a list of file paths (file1.txt, file2.txt, file3.txt) and retrieves the size of each file in bytes using the os.path.getsize() method, then prints the sizes alongside their respective filenames.

Python3

import os

file_paths = [ 'file1.txt' , 'file2.txt' , 'file3.txt' ]

for file_path in file_paths:

`` size = os.path.getsize(file_path)

`` print (f "Size of '{file_path}' in bytes:" , size)

**Output:

Size of 'file1.txt' in bytes: 1234
Size of 'file2.txt' in bytes: 5678
Size of 'file3.txt' in bytes: 9012