Python: Get file size in KB, MB, or GB – human-readable format

In this tutorial of getting the file size in KB, MB, or GB in Human-readable format in Python, we are going to see how we can get the sizes of different files in bytes, kilobytes, megabytes, gigabytes, etc.

Different ways to get file size in Bytes, Kilobytes, Megabytes, Gigabytes, etc

  1. Get file size using os.path.getsize()
  2. Get file size using os.stat().st_size
  3. Get size using pathlib.Path.stat().st_size
  4. Get file size in KiloBytes, MegaBytes, or GigaBytes

Method-1: Get file size in bytes using os.path.getsize()

In this function, we pass the path of the file into it and if the file exists it returns the file size in bytes. If the file does not exist it throws os.error.

Syntax:

Syntax : os.path.getsize(path)

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

Source Code:

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

import os
def fileSizeInBytes(filePath):
    """Size of the file in bytes"""
    sizeOfFile = os.path.getsize(filePath)
    return sizeOfFile
filePath = 'movie.mkv'
#Getting the size of the file from by passing the path into the function
sizeOfFile = fileSizeInBytes(filePath)
print('Size of the file(In Bytes) - ', sizeOfFile)
Output :
Size of the file(In Bytes) -  349016027

Method-2: Get file size in bytes using os.stat().st_size

We can also find the size of the file using a stats( ) function available in Python’s OS module. It takes the file path as an argument and returns an object containing the file details.

Syntax:

os.stat(path, *, dir_fd=None, follow_symlinks=True)

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

Source Code:

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

import os
def fileSizeInBytes(filePath):
    """Find the size of the file in bytes"""
    statOfFile = os.stat(filePath)
    #Size of file from the stats
    sizeOfFile = statOfFile.st_size
    return sizeOfFile
filePath = 'movie.mkv'
#Getting the size of the file from by passing the path into the function
sizeOfFile = fileSizeInBytes(filePath)
print('Size of the file(In Bytes) - ', sizeOfFile)
Output :
Size of the file(In Bytes) -  349016027

Method-3: Get file size in bytes using pathlib.Path.stat().st_size

 

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

from pathlib import Path
def fileSizeInBytes(filePath):
    """Size of the file in bytes"""
    fileObj = Path(filePath)
    #Size of file from the stats
    sizeOfFile = fileObj.stat().st_size
    return sizeOfFile
filePath = 'movie.mkv'
#Getting the size of the file from by passing the path into the function
sizeOfFile = fileSizeInBytes(filePath)
print('Size of the file(In Bytes) - ', sizeOfFile)
Output :
Size of the file(In Bytes) -  349016027

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

We can get the file sizes using the above method but we can not convert them to KB, MB, GB, TB directly so we have to create a function. The function would convert the units and so us the size of the file in our desired unit.

Here is a conversion table to switch from bytes to another unit of measurement :

Units Number of bytes
KiloBytes 1024
MegaBytes 1024*1024 = 1 048 576‬
GigaBytes 1024*1024*1024 = 1 073 741 824

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

#Program to Get file size in human-readable units like KB, MB, GB, TB

import enum
import os

class sizeUnit(enum.Enum):
    #class to store the various units
    BYTES = 1
    KB = 2
    MB = 3
    GB = 4

def unitConvertor(sizeInBytes, unit):
    #Cinverts the file unit
    if unit == sizeUnit.KB:
        return sizeInBytes/1024
    elif unit == sizeUnit.MB:
        return sizeInBytes/(1024*1024)
    elif unit == sizeUnit.GB:
        return sizeInBytes/(1024*1024*1024)
    else:
        return sizeInBytes

def fileSize(filePath, size_type):
    """File size in KB, MB and GB"""
    size = os.path.getsize(filePath)
    return unitConvertor(size, size_type)

filePath = 'movie.mkv'
sizeOfFile = fileSize(filePath,sizeUnit.BYTES)
print('Size of the file in - ', sizeOfFile)
#Printing the size of file in KB
sizeOfFile = fileSize(filePath,sizeUnit.KB)
print('Size of the file in KB - ', sizeOfFile)
#Printing the size of file in MB
sizeOfFile = fileSize(filePath,sizeUnit.MB)
print('Size of the file in MB - ', sizeOfFile)
#Printing the size of file in GB
sizeOfFile = fileSize(filePath,sizeUnit.GB)
print('Size of the file in GB - ', sizeOfFile)
Output :
Size of the file in -  349016027
Size of the file in KB -  340835.9638671875
Size of the file in MB -  332.8476209640503
Size of the file in GB -  0.32504650484770536

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

In case the file does not exist it will throw an error disrupting our program’s execution. So to handle that we can check if the file exists or not and if not then handle it by using the if-else block.

# Program to check if the file exists before checking for the size of the file

import os 

def fileSizeInBytes(filePath):
    """ Size of the file in bytes"""
    sizeOfFile = os.path.getsize(filePath)
    return sizeOfFile

#Passing a file name that does not exist into the program
fileName = 'nonExistentFile.txt'
if os.path.exists(fileName):
    size = fileSizeInBytes(fileName)
    print('Size of file in Bytes : ', size)
else:
    print('File not there')
Output :
File not there