Call Path("file.bin").stat().st_size from the built-in pathlib module (or os.path.getsize("file.bin")) to retrieve the exact file size in bytes as an int in $O(1)$ time via a single OS stat() syscall—without opening or reading the file contents into memory.
Basic Example
import os
from pathlib import Path
file_path = Path("example.txt")
file_path.write_text("Hello, Python!\n", encoding="utf-8")
# 1. Recommended (Modern object-oriented `pathlib` API):
size_bytes = file_path.stat().st_size
print(f"Size: {size_bytes} bytes")
# Output: Size: 15 bytes
# 2. Classic `os.path` helper (returns the exact same integer):
print(os.path.getsize("example.txt"))
# Output: 15
# 3. From an already-open file object (`os.fstat(f.fileno()).st_size`):
with open("example.txt", "rb") as f:
print(os.fstat(f.fileno()).st_size)
# Output: 15
Key Details & Edge Cases
- Symlink behavior (
Path.stat()vs.Path.lstat()):- Both
Path.stat().st_sizeandos.path.getsize()follow symbolic links by default, returning the byte size of the target file (and raisingFileNotFoundErrorif the symlink is broken). To measure the size of the symlink entry itself rather than its target, callPath("link").lstat().st_size.
- Both
- Never pass a directory path expecting recursive folder size:
- Calling
Path("some_folder").stat().st_sizereturns only the filesystem directory inode/metadata size (typically4096bytes on Linux or0on Windows)—not the total size of the files inside it. Sum files recursively instead:total_dir_bytes = sum( p.stat().st_size for p in Path("some_folder").rglob("*") if p.is_file() and not p.is_symlink() )
- Calling
- Avoid
len(f.read())to measure file size:- Reading an entire file just to call
len(...)wastes $O(N)$ RAM and disk I/O—and in text mode ("r"),len(f.read())returns the Unicode character count, which differs from the byte size whenever multi-byte UTF-8 characters (emojis, accented letters) or\r\nnewline translations are present.
- Reading an entire file just to call
- Formatting raw byte counts into human-readable units (
KB,MB,GB):- Python’s standard library returns exact bytes (
int). Format into binary (KiB/MiBusing1024) or decimal (KB/MBusing1000) units with a compact helper:def format_bytes(num_bytes: int, base: int = 1024) -> str: units = ["B", "KiB", "MiB", "GiB", "TiB"] if base == 1024 else ["B", "KB", "MB", "GB", "TB"] size = float(num_bytes) for unit in units[:-1]: if size < base: return f"{size:.2f} {unit}" size /= base return f"{size:.2f} {units[-1]}"
- Python’s standard library returns exact bytes (
- Checking file existence safely before querying
.st_size:- If the file might not exist, catch
FileNotFoundError(EAFP style) rather than checkingif path.exists():first, avoiding a TOCTOU race condition if the file is deleted between the check and.stat().
- If the file might not exist, catch
Comparison of File-Size Methods in Python
| Method | Follows Symlinks? | Requires Opening File? | Memory & Time Complexity | Best Used When |
|---|---|---|---|---|
Path(p).stat().st_size (Recommended) |
Yes (use .lstat() for symlink itself) |
No (single metadata syscall) | $O(1)$ memory, $O(1)$ time | Modern Python 3 codebases already using pathlib.Path objects (also gives .st_mtime, .st_mode). |
os.path.getsize(p) |
Yes | No (wraps os.stat(p).st_size) |
$O(1)$ memory, $O(1)$ time | Quick one-liner when working with plain str file paths. |
os.fstat(f.fileno()).st_size |
N/A (uses open file descriptor) | Uses existing open handle | $O(1)$ memory, $O(1)$ time | Querying the size of a file that is already open (e.g., inside with open(...) as f:). |
f.seek(0, os.SEEK_END) |
N/A | Yes (must open in "rb" mode) |
$O(1)$ memory, $O(1)$ time | Seekable binary streams (io.BytesIO or temp files) that may lack a filesystem path. |
You must log in or register to comment.
