To get the file size in Python, we can use the os
module which comes inbuilt with the Python.
Module os
has a sub-module path
. This sub-module has the getsize()
method associated with it. It can be used to get the size of the given file.
os.path.getsize(<file_path>) Arguments: path (string): file path Returns: int : size of the file in bytes
import os
file_path = "example.zip"
file_size = os.path.getsize(file_path)
print(f"Size of the file ({file_path}) is {file_size}")
If you are using only getsize()
method in your Python program, it is better to import only this method instead of complete os
module in your code.
from os.path import getsize
file_path = "example.zip"
file_size = getsize(file_path)
print(f"Size of the file ({file_path}) is {file_size}")
Output:
The output of the above both programs will be same.
Size of the file (example.zip) is 15787
Here, file example.zip
has to be in the same directory from where you are running your Python script. Otherwise, you can also provide absolute path of the file.
By default, it returns the file size in bytes. You can convert it into the human-readable format like KB, MB, GB…
If the file path is not valid, your program will throw an exception.
FileNotFoundError: [Errno 2] No such file or directory
If you are using the getsize()
method to find the size of the file, it is good practice to handle this exception in Python.
To avoid this exception, you can also check whether the given file is present or not.
Many times, we need to check the file size in Python before processing it. For example, you can avoid certain operations (like file read-write operations) if the size of the file is zero (empty file).
If you are building project where user needs to upload any file, you can check the file size. If the file size is zero, you can prompt user to upload valid file. You can also check if the file is greater than some threshold value.