Python os.path.getsize() Method



The Python os.path.getsize() method is used to retrieve the size of a file in bytes. It returns an integer representing the size of the specified file.

If the specified path does not exist or if there are permission issues preventing access to the path, the method raises a FileNotFoundError or PermissionError, respectively.

Syntax

Following is the basic syntax of the Python os.path.getsize() method −

os.path.getsize(path)

Parameter

This method accepts a string as a parameter representing the path to the file whose size you want to retrieve.

Return Value

The method returns an integer representing the size of the file in bytes.

Example

In the following example, we are retrieving the size of the file in bytes located at the given path "file_Path" −

import os
file_path = "/home/lenovo/documents/file.txt"
size = os.path.getsize(file_path)
print("The size of the file is:",size)

Output

The output obtained is as follows −

The size of the file is: 873

Example

Here, we are retrieving the size of the current directory and print it in bytes −

import os
current_dir = os.getcwd()
size = os.path.getsize(current_dir)
print("The size of the current directory is:",size)

Output

Following is the output of the above code −

The size of the current directory is: 16384

Example

This example retrieves the size of the symbolic link located at "/home/lenovo/symlink" and prints it in bytes −

import os
link_path = "/home/lenovo/symlink"
size = os.path.getsize(link_path)
print("The size of the symbolic link is:",size)  

Output

We get the output as shown below −

The size of the symbolic link is: 53

Example

If we attempt to retrieve the size of a non-existent file path "/non/existent/path", the getsize() method raises the "FileNotFoundError" −

import os
link_path = "/non/existent/path"
size = os.path.getsize(link_path)
print("The size of the file is:",size)    

Output

The result produced is as shown below −

Traceback (most recent call last):
  File "C:\Users\Lenovo\Desktop\untitled.py", line 3, in <module>
    size = os.path.getsize(link_path)
  File "<frozen genericpath>", line 62, in getsize
FileNotFoundError: [WinError 3] The system cannot find the path specified: '/non/existent/path'
os_path_methods.htm
Advertisements