How to Get the File Size in Python (Bytes, KB, MB)

To get the file size in Python, call os.path.getsize("file.csv") or Path("file.csv").stat().st_size. Both return the size in bytes; divide by 1024 ** 2 to get megabytes. This guide shows each way to get a file size in Python, converts bytes to KB, MB and GB (and explains why Windows and disk makers disagree), adds up the size of a folder, and handles missing and empty files.

All examples were run with Python 3.12.5 in the Windows Command Prompt. Reference: os.path.getsize() and Path.stat() in the Python docs.

Get the size of a file in bytes

The first part of the script only creates a few sample files so the example runs on its own:

import os
os.makedirs("reports", exist_ok=True)
with open("reports/sales.csv", "w") as f:
    f.write("id,amount\n" + "".join(f"{i},{i * 3.5}\n" for i in range(40_000)))
with open("reports/notes.txt", "w") as f:
    f.write("Quarterly notes\n" * 500)
os.makedirs("reports/archive", exist_ok=True)
with open("reports/archive/2024.bin", "wb") as f:
    f.write(os.urandom(3_500_000))

from pathlib import Path

print(os.path.getsize("reports/sales.csv"), "bytes")          # 1. os.path.getsize
print(Path("reports/sales.csv").stat().st_size, "bytes")      # 2. pathlib
print(os.stat("reports/sales.csv").st_size, "bytes")          # 3. os.stat

Output:

597153 bytes
597153 bytes
597153 bytes
Command Prompt output of a Python script creating sample files and printing a file size in bytes with os.path.getsize, pathlib stat and os.stat
Three ways, the same number of bytes.

Get the file size in MB (bytes to KB, MB, GB)

There are two conventions. Operating systems like Windows divide by 1024 (and call the result MB, strictly MiB); storage makers divide by 1000:

import os

size = os.path.getsize("reports/archive/2024.bin")

print(f"{size} bytes")
print(f"{size / 1024:.2f} KiB   {size / 1024 ** 2:.2f} MiB   (1 MiB = 1,048,576 bytes, what Windows shows as MB)")
print(f"{size / 1000:.2f} kB    {size / 1000 ** 2:.2f} MB    (1 MB = 1,000,000 bytes, what disk makers use)")

Output:

3500000 bytes
3417.97 KiB   3.34 MiB   (1 MiB = 1,048,576 bytes, what Windows shows as MB)
3500.00 kB    3.50 MB    (1 MB = 1,000,000 bytes, what disk makers use)
Command Prompt output converting a 3,500,000 byte file to KiB, MiB, kB and MB with 1024 and 1000 based units
The same file is 3.34 MB in Windows Explorer terms and 3.50 MB in decimal units.

A reusable human-readable size function

import os

def human_size(num_bytes, binary=True):
    """Format a byte count like 3.34 MB (binary=True uses 1024 steps)."""
    step = 1024 if binary else 1000
    for unit in ["bytes", "KB", "MB", "GB", "TB"]:
        if num_bytes < step or unit == "TB":
            return f"{num_bytes:.0f} {unit}" if unit == "bytes" else f"{num_bytes:.2f} {unit}"
        num_bytes /= step

for path in ["reports/notes.txt", "reports/sales.csv", "reports/archive/2024.bin"]:
    print(f"{path:<26} {human_size(os.path.getsize(path)):>10}")
print(human_size(5_368_709_120))

Output:

reports/notes.txt             8.30 KB
reports/sales.csv           583.16 KB
reports/archive/2024.bin      3.34 MB
5.00 GB

Get the total size of a folder

Path.rglob("*") walks through all subfolders; add up the sizes of the files:

from pathlib import Path

folder = Path("reports")
total = 0
for file in folder.rglob("*"):                 # every file in all subfolders
    if file.is_file():
        size = file.stat().st_size
        total += size
        print(f"{str(file):<28} {size:>10,} bytes")
print(f"{'total':<28} {total:>10,} bytes = {total / 1024 ** 2:.2f} MB")

Output:

reports\notes.txt                 8,500 bytes
reports\sales.csv               597,153 bytes
reports\archive\2024.bin      3,500,000 bytes
total                         4,105,653 bytes = 3.92 MB
Command Prompt output listing each file in a folder and subfolder with its size and the total folder size in MB using pathlib rglob
Every file and the folder total.

Missing files, empty files and size limits

import os
from pathlib import Path

try:
    os.path.getsize("reports/missing.csv")
except FileNotFoundError as e:
    print("FileNotFoundError:", e)

p = Path("reports/missing.csv")
print("size:", p.stat().st_size if p.exists() else "file does not exist")

size = os.path.getsize("reports/notes.txt")
print("empty file?", size == 0)
limit = 5 * 1024 ** 2
print("under 5 MB upload limit?", os.path.getsize("reports/archive/2024.bin") <= limit)

Output:

FileNotFoundError: [WinError 2] The system cannot find the file specified: 'reports/missing.csv'
size: file does not exist
empty file? False
under 5 MB upload limit? True
Command Prompt output of FileNotFoundError from os.path.getsize, a safe exists check, an empty-file check and an upload size limit check
Handle missing files, and use the size for simple checks.

Size of an open file, and a common mistake

For a file you already have open, seek to the end and call tell(). Do not use sys.getsizeof(): it measures the Python object in memory, not the file:

import os
import sys

with open("reports/sales.csv", "rb") as f:
    f.seek(0, os.SEEK_END)                 # jump to the end of the file
    print("size from seek/tell:", f.tell(), "bytes")

data = open("reports/sales.csv").read()
print("len of the text:", len(data), "characters")
print("sys.getsizeof(text):", sys.getsizeof(data), "bytes of memory (not the file size)")

Output:

size from seek/tell: 597153 bytes
len of the text: 557152 characters
sys.getsizeof(text): 557193 bytes of memory (not the file size)

On Windows the number of characters is smaller than the file size here, because every \n was written to disk as the two bytes \r\n.

GoalCode
Size in bytesos.path.getsize(path) or Path(path).stat().st_size
Size in MBos.path.getsize(path) / 1024 ** 2
Folder sizesum(f.stat().st_size for f in Path(d).rglob("*") if f.is_file())
Open filef.seek(0, os.SEEK_END); f.tell()

More Python file tutorials:

Frequently asked questions

How do I get the size of a file in Python?

os.path.getsize("file.txt") returns the size in bytes. With pathlib, use Path("file.txt").stat().st_size.

How do I get the file size in MB?

Divide the bytes by 1024 ** 2 (what Windows shows) or by 1_000_000 (decimal MB): os.path.getsize(p) / 1024 ** 2.

How do I convert bytes to MB in Python?

mb = num_bytes / (1024 * 1024), and format it with f"{mb:.2f} MB".

How do I get the size of a folder?

Add up the sizes of all files: sum(f.stat().st_size for f in Path("folder").rglob("*") if f.is_file()).

What happens if the file does not exist?

os.path.getsize() raises FileNotFoundError; check os.path.exists() first or catch the exception.

Why is sys.getsizeof() different from the file size?

It measures how much memory a Python object uses, not how many bytes a file has on disk.