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.
Demo
import os with open('notes.txt', 'wb') as f: f.write('hello world'.encode('utf-8')) (os.path.getsize('notes.txt'), len('hello world'))
'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
| Name | Type | Required | Description |
|---|---|---|---|
| path | str | bytes | PathLike | yes | An 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
import os newest = max((os.path.join(folder, n) for n in os.listdir(folder)), key=os.path.getmtime)
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))
import os, datetime modified = datetime.datetime.fromtimestamp(os.path.getmtime(path), tz=datetime.timezone.utc)
Examples
Pitfalls
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)
import os with open('notes.txt', 'w', encoding='utf-8', newline='\n') as f: f.write('a\nb\n') os.path.getsize('notes.txt')
import os try: size = os.path.getsize('maybe.log') except FileNotFoundError: size = 'raised' size
import os try: size = os.path.getsize('maybe.log') except FileNotFoundError: size = 0 size
When to use
- One quick fact about a file: its size or modification time
- Sorting files by date (key=os.path.getmtime)
- 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
FAQ
os.path.getsize(path) returns bytes. Path(path).stat().st_size is the pathlib equivalent.