What’s New ?

The Top 10 favtutor Features You Might Have Overlooked

Read More

How to Get File Size in Python? 4 Methods (with code)

  • Sep 14, 2023
  • 6 Minutes Read
  • Why Trust Us
    We uphold a strict editorial policy that emphasizes factual accuracy, relevance, and impartiality. Our content is crafted by top technical writers with deep knowledge in the fields of computer science and data science, ensuring each piece is meticulously reviewed by a team of seasoned editors to guarantee compliance with the highest standards in educational content creation and publishing.
  • By Shivali Bhadaniya
How to Get File Size in Python? 4 Methods (with code)

Learning Python can be complicated and difficult, but it is also one of the most valuable programming languages to learn. However, working with Python comes with working with lots of files. In this article, we will learn how to get the size of a file in Python using various methods with examples. So, let’s get started!

4 Methods to Get File Size in Python

In Python, determining the size of a file is crucial for many I/O tasks. Knowing the size of files may be useful for several things, including tracking progress during operations like downloads, uploads, and writing to disc.  Below are the methods by which Python gets file size:

Method 1) Using the os.path module

Python’s os.path module provides a getsize() function which returns the file size as the integer. Here, the function takes the file path as the argument and returns the size of the file in bytes. Check out the below example for a better understanding:

For example:

import os
file_size = os.path.getsize('d:/test_file.jpg')
print("File Size is :", file_size)

 

Output:

Size of file is : 512 

 

Method 2) Using stat function

Python’s os module provides the stat function which returns an integer as file size. This function takes a file path as the argument which may be a string or object and returns statistical details about the path provided. These statistical properties provide with “st_size” parameter which contains the size of the file(in bytes).

For example:

import os
file_size = os.path.getsize('d:/test_file.jpg')
print("File Size is :", file_size)

 

Output:

Size of file is : 512 

 

Method 3) Using file object

Python get file size using file object by following the below steps:

  • To open the file, use the open() function and save the resulting object in a variable. When you open the file, the cursor moves to the beginning of the file.
  • The file object supports the seek() method to move the pointer to the desired position. Simply put, it is used to set the cursor to the file’s end position. It takes two arguments: start and finish location.
  • The file object contains a tell() method that may be used to retrieve the current cursor location, which is equal to the number of bytes changed by the cursor. As a result, this function returns the file's size in bytes.

For example:

file = open('d:/test_file.jpg')
file.seek(0, os.SEEK_END)
print("File Size is :", file.tell())

 

Output:

Size of file is : 512 

 

Method 4) Using the pathlib module

The Path object's stat() function returns file characteristics such as "st_mode", "st_dev", and so on. Furthermore, the stat method's "st_size" property returns the file size in bytes. Check out the below example for a better understanding. 

For example:

from pathlib import Path
Path(r'd:/test_file.jpg').stat()
file=Path(r'd:/test_file.jpg').stat().st_size
print("File Size is :", file)

 

Output:

Size of file is : 512 

 

How do you find the MB size in Python?

In Python, you may ascertain the size of an object by using the sys module, which offers access to several variables utilized or maintained by the interpreter as well as functions that interact heavily with the interpreter.

The getsizeof() function from the sys module can be used to calculate the size of an object in memory. This function usually returns the size of the object in bytes. An example code on how to find the size of an object using python:

import sys

my_list = [1, 2, 3, 4, 5]
size = sys.getsizeof(my_list)
print(size) 

 

Output:

96

 

In the above example, we have imported the sys module and created an integer list. The getsizeof() function is then used to determine the size of the list object in memory and stores the result in the size variable. Finally, we obtain the result, which is the size of the list object in bytes.

Get Size of all Files in a Directory

The os and os.path modules in Python can be used to get the size of all files in a directory. The os module contains functions for interacting with the operating system, and the os.path module has functions to work with paths.

An example code that demonstrates how to get the size of all files in a directory:

import os
directory = "/path/to/directory"
# Get all the files in the directory
files = os.listdir(directory)
# Iterate over all the files and get their size
total_size = 0
for file in files:
    file_path = os.path.join(directory, file)
    # Check if the file is a regular file (not a directory)
    if os.path.isfile(file_path):
        # Get the size of the file in bytes and add it to the total size
        total_size += os.path.getsize(file_path)

print(f"Total size of all files in directory: {total_size} bytes")

 

In the above code, we begin by importing the os module.

  • And in the next step we have specified the directory whose files we wish to know the size of by setting the directory variable to the directory's path.
  • To retrieve a list of all the files in the directory, we use the os.listdir() function.
  • We have used a for loop to cycle over the list of files and get the path of each file by joining the directory path and the file name with the os.path.join() function.
  • Using the os.path.isfile() function, we determined whether the file is an ordinary file (rather than a directory).
  • If the file is a regular file, we use os.path.getsize() to get the file size in bytes and add it to the total_size variable.
  • Finally, we have printed the total size in bytes of all the files in the directory.

Conclusion

In this article, we studied how Python checks file size using four different methods as well as examples and output. If you still have any doubts, our Python Tutors are available 24/7 online to help you.

FavTutor - 24x7 Live Coding Help from Expert Tutors!

About The Author
Shivali Bhadaniya
I'm Shivali Bhadaniya, a computer engineer student and technical content writer, very enthusiastic to learn and explore new technologies and looking towards great opportunities. It is amazing for me to share my knowledge through my content to help curious minds.