Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

For one file, use os.path.getsize(path) or Path(path).stat().st_size; both return a logical size in bytes. For a folder’s contents, walk its files and add their sizes. A directory’s own st_size is not the total size of everything inside it.

Get the size of one file

The simplest option is os.path.getsize(). Give it a file path, and it returns the file’s size as an integer number of bytes. For example:

import os

size_bytes = os.path.getsize("report.pdf")
print(size_bytes)

The equivalent using pathlib is to call stat() and read its st_size field:

from pathlib import Path

size_bytes = Path("report.pdf").stat().st_size
print(size_bytes)

These methods are for a path that identifies a file. They raise an OSError if the path is missing or cannot be accessed, so decide whether your program should stop, report the problem, or handle it and continue.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
#1 Best Overall
Elebase USB to USB C Adapter for iPhone 18 Pro Max,USBC Car Charger Adapter
  • Read Before You Buy — No Video Output: These adapters support charging and USB 2.0 data transfer, but cannot transmit video signals. Except for standard USB webcams (which use USB data only), they are not compatible with HDMI/DisplayPort cables, video-capable USB-C hubs, or docking stations with video output.
  • Convert USB-A Ports to USB-C: Designed to connect USB-C earphones, cables, flash drives, card readers, and other USB-C accessories to standard USB-A ports. Plug-and-play with no drivers or software required.
  • Aluminum Alloy Housing: Built with a sturdy aluminum alloy shell that aids in heat dissipation and protects against daily wear and scratches. Designed to maintain a stable and secure connection.
  • Compact & Travel-Friendly: The ultra-compact design allows the adapter to stay plugged into your device without blocking adjacent ports or adding bulk, reducing wear and tear on your original USB ports.
  • 12-Month Warranty: Backed by a 12-month manufacturer warranty for peace of mind. Designed to meet strict quality control standards for reliable everyday performance.

Use the value as bytes

Keep the original integer for comparisons, limits, and calculations. Convert to a human-readable unit only when displaying it. The following helper uses binary units, where each step is 1,024 bytes:

def human_bytes(n: int) -> str:
    units = ["B", "KiB", "MiB", "GiB", "TiB"]
    value = float(n)
    for unit in units:
        if value < 1024 or unit == units[-1]:
            return f"{value:.1f} {unit}"
        value /= 1024

print(human_bytes(size_bytes))

For example, this helper will display 1,048,576 bytes as 1.0 MiB. It formats the number; it does not change the underlying byte count.

Calculate a folder’s total size recursively

A folder total is the sum of the sizes of the files you choose to include beneath that folder. Python’s os.walk() is a straightforward way to visit the tree. This version sums readable files and skips paths that raise OSError:

import os


def folder_size(path: str) -> int:
    total = 0
    for root, dirs, files in os.walk(path):
        for name in files:
            file_path = os.path.join(root, name)
            try:
                total += os.path.getsize(file_path)
            except OSError:
                # Replace with logging or re-raise if skipped files matter.
                pass
    return total

print(folder_size("my_folder"))

The return value is an integer byte count. The error handler is a policy choice, not a guarantee that the result includes every file: if a file disappears or access is denied during traversal, this example skips it. For backups, audits, or billing calculations, you may prefer to record skipped paths or fail rather than silently return a partial total.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Exclude directories while walking

os.walk() provides a mutable dirs list for each visited directory. Remove entries from it to prune subtrees before they are traversed. This example excludes every directory named __pycache__:

Rank #2
Anker USB-C Hub, 5-in-1 USB Hub for Laptops, 4K HDMI Multiport Adapter
  • 5-in-1 USB-C Hub: Experience comprehensive connectivity featuring a Power Delivery input, two USB-A 2.0 ports, a USB-A 3.0 port, and an HDMI port. (Note: The USB-C power delivery input port is only for connecting an external wall charger to power your laptop and cannot power peripheral devices.)
  • 90W Pass-Through Charging: Achieve optimal charging with 90W pass-through power to your laptop, supported by a total input of 100W, with the hub reserving 10W for operational efficiency. (Note: Wall charger not included.)
  • Quick Data Transfers: Accelerate your productivity with rapid data transfers using a high-speed 5Gbps USB 3.0 port and two 480Mbps USB 2.0 ports.
  • 4K HDMI Display: Enhance your visual experience with a hub capable of delivering 4K resolution at 30Hz in both mirror and extend modes. Please note that this hub is compatible with MacBook (macOS 12 and newer), Windows 10 and 11, ChromeOS, and laptops equipped with DP Alt Mode and Power Delivery. Note: This device is not compatible with Linux.
  • What You Get: Anker USB-C Hub (5-in-1, 4K HDMI), welcome guide, 18-month warranty, and our friendly customer service.
import os


def folder_size_without_pycache(path: str) -> int:
    total = 0
    for root, dirs, files in os.walk(path):
        dirs[:] = [name for name in dirs if name != "__pycache__"]
        for name in files:
            try:
                total += os.path.getsize(os.path.join(root, name))
            except OSError:
                pass
    return total

Pruning matters when excluded folders may be large: it avoids visiting their contents, rather than merely leaving their file sizes out of the final sum.

Use pathlib on Python 3.12 and later

Path.walk() offers a pathlib-style traversal, but it requires Python 3.12 or later. The following sums file sizes under a directory:

from pathlib import Path


def folder_size(path: Path) -> int:
    total = 0
    for root, dirs, files in path.walk():
        for name in files:
            try:
                total += (root / name).stat().st_size
            except OSError:
                pass
    return total

print(folder_size(Path("my_folder")))

As with the os.walk() version, remove excluded names from dirs if you want to prune folders. For example, add dirs[:] = [name for name in dirs if name != "__pycache__"] inside the loop before processing files. If you need to support Python versions before 3.12, use os.walk() or another available traversal method instead.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Choose the traversal and symlink policy

The right implementation depends on which paths count toward your total, how you want errors handled, and which Python version you support.

Approach When it fits Important behavior
os.path.getsize() Checking one path Returns bytes; raises OSError for missing or inaccessible paths.
Path.stat().st_size Checking one path with pathlib Returns the stat result’s size; stat() follows a symlink.
os.walk() Recursive folder totals and broad Python-version compatibility Does not descend into directory symlinks by default. Setting followlinks=True can loop if links point back to an ancestor.
Path.walk() Recursive traversal with pathlib on Python 3.12+ Use dirs to prune subtrees; decide how to handle per-file errors and links.
os.scandir() Directory iteration where entry metadata is useful DirEntry provides path and stat methods; stat calls can raise OSError.

Decide whether links count

For a file symlink, Path.stat() follows the link and reports the target’s size. Path.lstat() instead reports information about the link itself. Be explicit about which meaning you need; otherwise, a total can include target data when you expected only the link entry.

Rank #3
Sale
Anker USB C Hub, 7in1 Multi-Port USB Adapter, 4K@60Hz USBC to HDMI Splitter
  • Sleek 7-in-1 USB-C Hub: Features an HDMI port, two USB-A 3.0 ports, and a USB-C data port, each providing 5Gbps transfer speeds. It also includes a USB-C PD input port for charging up to 100W and dual SD and TF card slots, all in a compact design.
  • Flawless 4K@60Hz Video with HDMI: Delivers exceptional clarity and smoothness with its 4K@60Hz HDMI port, making it ideal for high-definition presentations and entertainment. (Note: Only the HDMI port supports video projection; the USB-C port is for data transfer only.)
  • Double Up on Efficiency: The two USB-A 3.0 ports and a USB-C port support a fast 5Gbps data rate, significantly boosting your transfer speeds and improving productivity.
  • Fast and Reliable 85W Charging: Offers high-capacity, speedy charging for laptops up to 85W, so you spend less time tethered to an outlet and more time being productive.
  • What You Get: Anker USB-C Hub (7-in-1), welcome guide, 18-month warranty, and our friendly customer service.

For directory links, the default os.walk() behavior is not to descend into them. Turning on followlinks=True changes what the traversal includes, and can cause infinite recursion when a link points to one of its parent directories. Only enable it when following directory links is intentional and your traversal accounts for cycles. The sample folder-total function does not follow directory symlinks.

Use scandir when entry checks are useful

os.walk() already uses os.scandir() internally. If you need direct access to directory entries—for example, to inspect entry types while iterating—you can use DirEntry methods. This example counts regular files in each directory without following file symlinks:

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
import os


def folder_size(path: str) -> int:
    total = 0
    for root, dirs, files in os.walk(path):
        with os.scandir(root) as entries:
            for entry in entries:
                try:
                    if entry.is_file(follow_symlinks=False):
                        total += entry.stat(follow_symlinks=False).st_size
                except OSError:
                    # Choose whether to log, skip, or re-raise.
                    pass
    return total

This illustrates entry-level type and metadata checks; it also calls os.walk() to enumerate directories. For a simple recursive sum, the earlier os.walk() version is easier to read. Any stat operation may fail while the tree is changing or access is restricted.

Understand what the total measures

These examples add logical file sizes—the st_size values—in bytes. That is not necessarily the amount of physical storage allocated on a filesystem. Sparse or compressed files can have a logical size that differs from their allocated disk blocks.

A folder-content total is also different from filesystem capacity. To ask how much space the filesystem has in total, uses, or has free, call shutil.disk_usage():

Rank #4
Sale
UGREEN USB to USB C Adapter Combo 4-Pack, 10Gbps USB C Converter Space Gray
  • Dual Converters, Infinite Potential:Includes 2× USB C male to USB A female adapters and 2× USB A male to USB C female adapters. Perfect for a wide range of uses—tablets with Bluetooth keyboards, expand USB ports on macbook, and more. Two different converters for all your daily needs
  • Next-Level 10Gbps & 3A Charging: No more slow 480Mbps, this usb to usb c adapter has a transfer speed of up to 10Gbps, allowing you to do more transferring in less time. This usb adapter fits both USB A and USB C charger, supporting up to 3A fast charging
  • Upgraded Exquisite Craftsmanship: With an aluminum alloy housing and metal connector, the usbc to usb adapter is extremely durable and sturdy. Rigorously tested to withstand more than 10,000 times of plugging and unplugging, ensuring long-lasting performance
  • Broad Compatible: The usb c to usb adapter widely supports all USB C/ USB A devices like laptops, tablets, cellphones, car chargers, and phone chargers. Such as compatible with MacBook Pro/Air 2023/2022, Thunderbolt 4/3 Devices,Apple MagSafe Watch 9/8/7/SE/Ultra, iPad Pro 2022/2021, Samsung Galaxy S23/S20/S10, and iPhone 17/16/15 Pro. Plug and play
  • Please Note: To reach 10Gbps speed, keep the cable under 3.3 ft. For USB A Male to USB C adapters, try flipping the USB C connector. USB C Male to USB A adapters support bidirectional 10Gbps transfer within 3.3 ft
import shutil

usage = shutil.disk_usage("my_folder")
print("total:", usage.total)
print("used:", usage.used)
print("free:", usage.free)

Those named fields are capacity figures in bytes for the filesystem containing the supplied path. They do not tell you how many logical bytes are inside that particular folder.

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Handle errors and changing directories

A recursive size calculation is a traversal-time estimate, not a transactionally consistent snapshot. Files can be created, removed, resized, or made inaccessible while your code walks the tree. A file that vanishes between discovery and stat, or a permissions change, can cause getsize(), Path.stat(), or DirEntry.stat() to raise OSError.

Pick an error policy that fits the use case:

  • Fail fast: let the exception propagate when a partial answer would be misleading.
  • Report and continue: catch OSError, record the path and error, then include the skipped-path count in the result.
  • Skip quietly: suitable only when omissions are acceptable and the total is clearly understood as best-effort.

For security-sensitive or audit work, also consider that symlink targets and file contents can change during traversal. A simple walk-and-sum does not lock the tree or make the result atomic.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Troubleshoot common size mismatches

A directory reports only a small number

That is the directory entry’s own metadata size, not a recursive total. Walk the descendants and sum file sizes to measure contents.

The result is smaller than the space used on disk

You may be comparing logical file bytes with allocated storage, which can differ for sparse or compressed files. You may also be excluding inaccessible files or directory symlinks. Check the traversal and error policy before interpreting the difference.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Best Value
Anker USB C Hub, 5-in-1 USBC to HDMI Splitter with 4K Display
  • 5-in-1 Connectivity: Equipped with a 4K HDMI port, a 5 Gbps USB-C data port, two 5 Gbps USB-A ports, and a USB C 100W PD-IN port. Note: The USB C 100W PD-IN port supports only charging and does not support data transfer devices such as headphones or speakers.
  • Powerful Pass-Through Charging: Supports up to 85W pass-through charging so you can power up your laptop while you use the hub. Note: Pass-through charging requires a charger (not included). Note: To achieve full power for iPad, we recommend using a 45W wall charger.
  • Transfer Files in Seconds: Move files to and from your laptop at speeds of up to 5 Gbps via the USB-C and USB-A data ports. Note: The USB C 5Gbps Data port does not support video output.
  • HD Display: Connect to the HDMI port to stream or mirror content to an external monitor in resolutions of up to 4K@30Hz. Note: The USB-C ports do not support video output.
  • What You Get: Anker 332 USB-C Hub (5-in-1), welcome guide, our worry-free 18-month warranty, and friendly customer service.

The function raises FileNotFoundError or PermissionError

Both are forms of OSError. Confirm that the path exists and that the process can access it. If the tree may change during the walk, choose whether that condition should stop the calculation or be logged and skipped.

The total seems unexpectedly large

Check whether file symlinks are being followed, whether the same target is reachable through more than one path, and whether your traversal follows directory symlinks. Avoid enabling followlinks=True without a cycle policy.

The pathlib folder example does not run

Path.walk() is available in Python 3.12 and later. Check your interpreter version; for earlier versions, use os.walk().

Or skip the browser setup

ScreenshotNeo is a website screenshot API and MCP server; it is a separate tool, not a way to measure Python file or folder sizes. If your project also needs website captures, its one-call endpoint returns an image or PDF. For example, this cURL request saves a WebP screenshot:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp

See the ScreenshotNeo API documentation for request options. Its clean-shot options can accept cookie or consent banners and remove more than 60 known consent platforms, newsletter popups, and chat widgets before capture; each step can be turned off. Bot checks or CAPTCHAs, blank pages, timeouts, failed loads, and cache hits cost nothing, and responses identify the page verdict and billing status in headers. An MCP server provides take_screenshot, get_page_info, and capture_pdf tools for AI agents and MCP clients. The Free plan includes 1,000 shots per month with no card; paid plans start at $5 for 3,000 shots.

Sign up for ScreenshotNeo’s free plan to get 1,000 screenshots a month with no card.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.