File Size Analyzer Function

  • Share this:

Code introduction


The function accepts a file path as an argument and returns the file size in a human-readable format (such as 1.23 KB).


Technology Stack : os, re, sys, time, json, math

Code Type : Function

Code Difficulty : Intermediate


                
                    
import os
import re
import sys
import time
import json
import math

def analyze_file_size(file_path):
    """
    Analyze the size of a file in human-readable format.

    Args:
        file_path (str): The path to the file to analyze.

    Returns:
        str: The size of the file in a human-readable format.
    """
    if not os.path.exists(file_path):
        return "File does not exist."

    file_size = os.path.getsize(file_path)
    for unit in ['bytes', 'KB', 'MB', 'GB', 'TB']:
        if file_size < 1024:
            return f"{file_size} {unit}"
        file_size /= 1024
    return f"{file_size:.2f} TB"                
              
Tags: