Menu Close

Top 5 Ways to Get File Size in Python

Get file size in Python

Hello Python programmers, I hope you are doing well. Sometimes it’s crucial to get file size in Python to perform operations like monitoring, logging file management, etc. As a Python programmer, I have faced this issue multiple times but now I can get the file size with the help of Python.

So I have decided to write a complete article on it, that’s why I am writing this article, throughout this article, we will explore various ways to get the file size in Python, complete with explanations and examples.

Except for getting file size, we will also write a Python function to return the appropriate file size like KB, MB, or GB.

As Python programmers, In real-life applications, Sometimes we may need to perform operations based on the size of the file. Then You can use these examples.

Here we will explore the top 5 proven ways to get file size and there is no requirement of any external Python libraries, You can achieve file size just by using a built-in Python module.

Now it’s time to see all the 5 ways to get the file size in Python.

So let’s get started

5 Ways to Get File Size in Python

We are using the following Python ways to get the file size.

  • Using Python os module
  • Using pathlib module
  • Using open() function
Note:- The file size will be returned in bytes in all the examples. If you want to convert it into KB, MB, or GB then we need to perform some calculations. Don't worry We will also see the calculation at the last of the article.

Using os.path.getsize()

The Python OS module provides a straightforward way to get the size of a file using the os.path.getsize() function. This method is simple and effective for most use cases.

import os

file_path = "C:\\Users\Vishvajit Rao\OneDrive\Desktop\emp.json"

file_size = os.path.getsize(file_path)
print("file size is {} bytes".format(file_size))
Get File Size in Python

Explanation:

  • Importing Python os module
  • file_path: The path to the file whose size you want to retrieve.
  • os.path.getsize(file_path): This function returns the size of the file specified by file_path in bytes.

os.stat()

The os.stat() function provides more detailed file information, including file size. This method can be useful if you need additional file metadata.

import os
file_path = "C:\\Users\Vishvajit Rao\OneDrive\Desktop\emp.json"
file_info = os.stat(file_path)
print("file size is {} bytes".format(file_info.st_size))
Get File Size in Python

Explanation

  • Importing Python os module
  • os.stat(file_path): Returns an os.stat_result object containing various statistics about the file.
  • file_info.st_size: Accesses the size of the file in bytes from the os.stat_result object
  • Displaying the size of the file.

Using pathlib Module

The pathlib module, introduced in Python 3.4, offers a more modern approach to file and path manipulation. It provides an object-oriented way to interact with filesystem paths.
If You are not familiar with Object-oriented programming, You can check out our Python Object Oriented tutorial.

import pathlib
file_path = "C:\\Users\Vishvajit Rao\OneDrive\Desktop\emp.json"
file_object = pathlib.Path(file_path)
size = file_object.stat().st_size
print(f"The size of the file is {size} bytes.")
Get File Size in Python

Explanation:

  • Importing Python pathlib module.
  • Path(file_path): Creates a Path object representing the file.
  • file_path.stat(): Returns a os.stat_result object similar to os.stat().
  • file_path.stat().st_size: Accesses the size of the file in bytes.
  • Printing the file size.

Using os.scandir()

If you have a directory with many files, os.scandir() can be more efficient than os.listdir() to get the file size. This method also allows you to get file sizes while iterating over directory contents.

import os

directory = "C:\\Users\Vishvajit Rao\OneDrive\Desktop\wheel"
with os.scandir(directory) as entries:
    for entry in entries:
        if entry.is_file():
            print(f"{entry.name}: {entry.stat().st_size} bytes")
Get File Size in Python

As you can see in the above Output, the file size of all three files has been displayed.

Explanation:

  • os.scandir(directory): Returns an iterator of os.DirEntry objects for the directory contents.
  • entry.stat().st_size: Retrieves the size of each file.

Using FileIO Object

For more control over file handling, you can use a file object to get its size by seeking the end of the file.

import os

file_path = "C:\\Users\Vishvajit Rao\OneDrive\Desktop\emp.json"
with open(file_path, 'rb') as file:
    file.seek(0, os.SEEK_END)
    size = file.tell()
print(f"The size of the file is {size} bytes.")
Get File Size in Python

Explanation

  • file.seek(0, os.SEEK_END): Moves the file pointer to the end of the file.
  • file.tell(): Returns the current file pointer position, which corresponds to the file size in bytes.

This is how you can get file size in Python using various ways one thing you have to remember, all these methods will return value in bytes.

If you want to get proper file size in appropriate ways like 10KB, 10MB, or 10GB then you will have to perform some calculations.

So let’s see how we can do that.

import os


def get_file_size(file_path):
    # Get the file size in bytes
    size_bytes = os.path.getsize(file_path)

    # Define size thresholds
    KB = 1024
    MB = KB * 1024
    GB = MB * 1024

    # Determine the human-readable size
    if size_bytes < KB:
        return f"{size_bytes} bytes"
    elif size_bytes < MB:
        return f"{size_bytes / KB:.2f} KB"
    elif size_bytes < GB:
        return f"{size_bytes / MB:.2f} MB"
    else:
        return f"{size_bytes / GB:.2f} GB"


file_path = "C:\\Users\Vishvajit Rao\OneDrive\Desktop\emp.json"
file_size = get_file_size(file_path)
print("File size is the {}".format(file_size))

Explanation:

  • Import the os Module: To use os.path.getsize() to get the file size in bytes.
  • Define Size Thresholds:
    • KB (Kilobyte) = 1024 bytes
    • MB (Megabyte) = 1024 KB
    • GB (Gigabyte) = 1024 MB
  • Determine the File Size Format:
    • Bytes: For files smaller than 1 KB.
    • KB: For files between 1 KB and 1 MB.
    • MB: For files between 1 MB and 1 GB.
    • GB: For files larger than 1 GB.
  • Formatting:
    • Use :.2f in the string formatting to round the size to two decimal places for clarity.

This is how you can get human readable file size using Python.


See Also:


Conclusion

So now we can get file size in Python using various ways. You can use any one of the above to get file size in Python and also you can achieve human-readable file size in Python.

Being a Popular language Python offers multiple methods to get the size of a file, each with its advantages. The choice of method depends on your specific needs:

  • Use os.path.getsize() for simplicity.
  • Use os.stat() or pathlib. Path if you need additional file metadata.
  • Use os.scandir() for directory traversal.
  • Use file objects for precise control over file operations.

By understanding and utilizing these methods, you can efficiently handle file sizes in your Python programs.

If you found this article helpful, please share and keep visiting for further articles.

Happy Learning…

Python PIP Tutorial with Examples

Related Posts