os.path.getsize

Each is os.stat(path) and one attribute: st_size, st_mtime, st_atime, st_ctime. Size is in bytes (not characters); getctime means "last metadata change" on Unix but "creation time" on Windows. Unlike exists(), these raise FileNotFoundError for a missing path.

os.path functionPython 3.0+Live demo
Common call
os.path.getsize(path)
Returns
1024
Replaces
len(open(path, "rb").read())
Watch out
getctime is not creation time on Linux/macOS
os.path.getsize(path) / getmtime(path) / getatime(path) / getctime(path)
→ int | float

Demo

Live evaluation
Write text as UTF-8 bytes and measure the file.
Try:
Inputs
textstrfile content
Code
import os
with open('notes.txt', 'wb') as f:
    f.write('hello world'.encode('utf-8'))
(os.path.getsize('notes.txt'), len('hello world'))
Result
(11, 11)

'Grüße, 世界' is 9 characters but 15 bytes: ü and ß take two bytes in UTF-8, each CJK character three. The times come back as floats exactly as set (whole seconds survive the round trip); real modification times usually have a fractional part. getctime is not shown: it cannot be set with utime, and its meaning differs between Windows and Unix.

Parameters

NameTypeRequiredDescription
pathstr | bytes | PathLikeyesAn existing file or folder; OSError otherwise.

Return value

int | float — getsize: int bytes. getmtime / getatime / getctime: float seconds since 1970-01-01 UTC.

Common patterns

Newest file in a folder
max with getmtime as the key.
import os
newest = max((os.path.join(folder, n) for n in os.listdir(folder)), key=os.path.getmtime)
Human-readable size
Divide by 1024 until it fits.
import os
def human(n):
    for unit in ('B', 'KiB', 'MiB', 'GiB'):
        if n < 1024:
            return f'{n:.0f} {unit}'
        n /= 1024
    return f'{n:.1f} TiB'
human(os.path.getsize(path))
Modification time as a datetime
Pass a timezone to get an aware value.
import os, datetime
modified = datetime.datetime.fromtimestamp(os.path.getmtime(path), tz=datetime.timezone.utc)

Examples

1. Size in bytes
import os with open('data.bin', 'wb') as f: f.write(b'\x00' * 1024) os.path.getsize('data.bin')
Returns
1024
2. Missing file raises
import os try: os.path.getsize('missing.bin') except OSError as e: result = type(e).__name__ result
Returns
'FileNotFoundError'
3. Read back fixed times
import os open('f', 'w').close() os.utime('f', (1000000000, 1700000000)) (os.path.getmtime('f'), os.path.getatime('f'))
Returns
(1700000000.0, 1000000000.0)
4. As a UTC datetime
import os, datetime open('f', 'w').close() os.utime('f', (0, 1700000000)) datetime.datetime.fromtimestamp(os.path.getmtime('f'), tz=datetime.timezone.utc).isoformat()
Returns
'2023-11-14T22:13:20+00:00'
5. Pick the newer file
import os open('old', 'w').close() open('new', 'w').close() os.utime('old', (0, 1600000000)) os.utime('new', (0, 1700000000)) max(['old', 'new'], key=os.path.getmtime)
Returns
'new'
6. getctime is a float too
import os open('f', 'w').close() type(os.path.getctime('f')).__name__
Returns
'float'

Pitfalls

1. Counting characters instead of bytes
Text written in text mode on Windows also turns each \n into \r\n, so the same text has two sizes.
text mode, platform newlines
import os
with open('notes.txt', 'w', encoding='utf-8') as f:
    f.write('a\nb\n')
os.path.getsize('notes.txt') in (4, 6)
True
newline='\n' — same everywhere
import os
with open('notes.txt', 'w', encoding='utf-8', newline='\n') as f:
    f.write('a\nb\n')
os.path.getsize('notes.txt')
4
2. Calling getsize on a path that may be missing
Unlike exists(), getsize raises. Catch FileNotFoundError, or stat once and reuse the result.
unguarded
import os
try:
    size = os.path.getsize('maybe.log')
except FileNotFoundError:
    size = 'raised'
size
'raised'
default to 0
import os
try:
    size = os.path.getsize('maybe.log')
except FileNotFoundError:
    size = 0
size
0

When to use

Use it
  • One quick fact about a file: its size or modification time
  • Sorting files by date (key=os.path.getmtime)
Reach for something else
  • Several fields → one os.stat call
  • Creation time on Linux/macOS → st_birthtime where available (os.stat)
  • pathlib code → Path.stat().st_size / .st_mtime

Notes

CPython impl
genericpath: getsize = os.stat(f).st_size, getmtime = .st_mtime, getatime = .st_atime, getctime = .st_ctime
getctime
Unix: time of the last metadata change. Windows: creation time
getatime
Many systems update access times lazily or not at all (relatime / noatime mounts), so do not rely on it
Folders
getsize of a folder is file-system specific (often 4096 on Linux ext4, 0 on Windows NTFS) — it is not the size of the contents

FAQ

os.path.getsize(path) returns bytes. Path(path).stat().st_size is the pathlib equivalent.