Best Practice to Python Get User-Friendly File Size – Python File Operation

By | August 9, 2019

To get file size in python, we can use os.path.getsize() function, however, this function returns bytes of a file. In this tutorial, we will introduce you how to get a friendly file size.

python get file size

Import library

import os

Get file size

def getfilesize(file_path):
    size = os.path.getsize(file_path)

However, this size is byte, which is not friendly to users, we shoud format it.

Format size of file

def formatSize(bytes):
    try:
        bytes = float(bytes)
        kb = bytes / 1024
    except:
        return "Error"

    if kb >= 1024:
        M = kb / 1024
        if M >= 1024:
            G = M / 1024
            return "%.2fG" % (G)
        else:
            return "%.2fM" % (M)
    else:
        return "%.2fkb" % (kb)

So, we can modify our getfilesize(file_path) as:

def getfilesize(file_path):
    size = os.path.getsize(file_path)
    return formatSize(size)