How to get the size of a file in Python using os.path.getsize()?

Published on Aug. 22, 2023, 12:17 p.m.

To get the size of a file in Python, you can use the os.path.getsize() method from the os library. This method takes the path to the file as its input and returns the size of the file in bytes as an integer. Here is an example:

import os

filename = "/path/to/file.txt"
size = os.path.getsize(filename)
print(size)

This example gets the size of the file located at /path/to/file.txt and prints it to the console.

Note that os.path.getsize() will raise a FileNotFoundError if the file does not exist or is inaccessible. Also, some file systems may not provide an accurate size value for very large files, so the size value returned by os.path.getsize() should be treated as an estimate.

Using os.path.getsize() is useful when you need to check the size of a file before performing certain operations that may be affected by the size of the file, such as transferring or copying files between different locations or devices.

Tags: