In this article, we will discuss different ways to get file size in human-readable formats like Bytes, Kilobytes (KB), MegaBytes (MB), GigaBytes(GB) etc.

Different ways to get file size in Bytes

Get file size in bytes using os.path.getsize()

It accepts the file path as an argument and returns the size of a file at the given path in bytes.
If the file doesn’t exist at the given path or it is inaccessible, then it raises an os.error. Therefore, always check that file exist or not before calling this function.

Let’s use this function to get the size of a file in bytes,

Output:

Get file size in bytes using os.stat().st_size

Python’s os module provides a function to get the file statistics,

It accepts file path (a string) as an argument and returns an object of the structure stat, which contains various attributes about the file at a given path. One of the attributes is st_size, which has the size of the file in bytes.

Let’s use this function to get the size of a file in bytes,

Output:

Get file size in bytes using pathlib.Path.stat().st_size

Let’s use pathlib module to get the size of a file in bytes,

Output:

In all the above techniques, we got the file size in bytes. What if we want file size in human-readable format like, KilloBytes, Megabytes or GigaBytes etc.

Get file size in human-readable units like kilobytes (KB), Megabytes (MB) or GigaBytes (GB)

1 KilloByte == 1024 Bytes
1 Megabyte == 1024*1024 Bytes
1 GigaByte == 1024*1024*1024 Bytes

We have created a function to convert the bytes into kilobytes (KB), Megabytes (MB) or GigaBytes (GB) i.e.

Let’s create a function to get the file size in different size units. This function internally uses to the above function to convert bytes into given size unit,

Let’s use this function to get the size of a given file in KB, MB or GB,

Get size of a file in Kilobyte i.e. KB

Output:

Get size of a file in Megabyte  i.e. MB

Output:

Get size of a file in Gigabyte  i.e. GB

Output:

Check if file exists before checking for the size of the file

If the file does not exist at the given path, then all the above created function to get file size can raise Error. Therefore we should first check if file exists or not, if yes then only check its size,

Output:

As file ‘dummy_file.txt’ does not exist, so we can not calculate its size.

The complete example is as follows,

Output:

Python Recommendations:

C++ & C++11 Recommendations:

If you didn't find what you were looking, then do suggest us in the comments below. We will be more than happy to add that.

Subscribe with us to join 1500+ Python & C++ developers, to get more Tips &  Tutorials like this.