October DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsClean PCRecommendedOne scan can reveal what keeps slowing WindowsLook for cleanup and repair opportunities.Run ScanOctober DealsAmazon USDeal season is back - check today's better picksAmazon US: current deals, useful picks and tech finds.See Picks×
Skip to content
World desk3 min

How to Get a File’s Size in Python (Bytes, KB, and MB)

Get an ordinary file’s size in Python with os.path.getsize() or Path.stat().st_size, then convert bytes to decimal or binary units.

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.

For an ordinary file, call os.path.getsize(path) or read Path(path).stat().st_size. Both return the size in bytes. To display KB or MB, divide that byte count by the decimal or binary unit you intend to use.

Get a file size in bytes

The simplest option is os.path.getsize():

import os

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

It returns the size in bytes and accepts path-like objects in Python 3.6 and later. The call raises OSError if the path does not exist or cannot be accessed. See the Python 3.14 os.path documentation.

If your code uses pathlib, read st_size from the path’s stat result:

from pathlib import Path

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

For an ordinary file, st_size is its size in bytes. Path.stat() returns a broader status result, which is useful if you need other file metadata too. See the Python 3.14 pathlib documentation.

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

Convert bytes to KB, MB, KiB, or MiB

The APIs return bytes; converting to larger units is arithmetic for display. Decimal units divide by powers of 1,000. Binary units divide by powers of 1,024. For clarity, label binary results KiB and MiB rather than KB and MB.

size_kb = size_bytes / 1_000
size_mb = size_bytes / 1_000_000

size_kib = size_bytes / 1_024
size_mib = size_bytes / (1_024 ** 2)

For example, to display a file size in binary mebibytes to two decimal places:

from pathlib import Path

size_bytes = Path("report.pdf").stat().st_size
size_mib = size_bytes / (1024 * 1024)
print(f"{size_mib:.2f} MiB")

Some interfaces label binary values KB and MB. If you are matching one, use its convention deliberately: dividing by 1,024 and 1,048,576 produces KiB and MiB, even if the interface calls them KB and MB.

Choose between os.path.getsize() and Path.stat().st_size

Option Use it when What you get
os.path.getsize(path) You want a direct byte-count call or your code already uses os.path. A size in bytes.
Path(path).stat().st_size Your code already uses pathlib, or you may also need other stat information. A size in bytes, read from the stat result.

Both are standard-library options; choose based on the style and information your code needs. Neither call locks the file. The value is a filesystem status snapshot and can become outdated if the file changes afterward.

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

Handle missing or inaccessible paths

When a lookup can fail, catch OSError rather than treating the error as a zero-byte file:

from pathlib import Path

try:
    size_bytes = Path("report.pdf").stat().st_size
except OSError as exc:
    print(f"Could not read file size: {exc}")
else:
    print(f"{size_bytes} bytes")

This handles failures such as a missing path or insufficient access. Decide in your application whether to report the error, retry, or take another action.

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

What happens with symbolic links and special files?

Normal os.path.getsize() and Path.stat() calls follow symbolic links, so they report the target’s size. To inspect the link itself instead, use Path(path).lstat().st_size. The Path.stat(follow_symlinks=False) option is documented as available from Python 3.10. See the Python 3.14 os.stat documentation.

A symbolic link’s own reported size is the length of its stored pathname, without a terminating null byte. For special files, st_size may not describe ordinary file contents: on many Unix systems, a FIFO or socket can report the bytes waiting to be read, and behavior for other special files varies by implementation. These examples are intended for ordinary files; see the Python 3.14 stat documentation for details.

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

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.

Leave a Reply

Your email address will not be published. Required fields are marked *

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.

More from the Wire

  1. World desk4 min
    How to Spot an AI Voice Scam Before Sending MoneyDon’t rely on how a caller sounds. Pause, call back through a known number, and verify the emergency with another trusted person before sending money.
  2. Mountain View desk4 min
    Google’s SynthID Detector: How to Check AI-Generated Images, Video and AudioGoogle’s SynthID Detector looks for an embedded watermark in supported images, video and audio. Here is what its results do—and do not—show.
  3. Redmond desk20 min
    How to create a link to File or Folder in Windows 11Windows 11 gives you several ways to point to a file or folder without moving or duplicating it. You can create a desktop shortcut,…
Recommended PC Tool
Recommended PC Tool
PC Slower Than It Used to Be?Free scan - under a minute
Outdated Drivers Are Slowing You DownFree scan - exact matches

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.