0
0
PythonHow-ToBeginner · 3 min read

How to Get File Size in Python: Simple Methods Explained

To get a file size in Python, use os.path.getsize(path) which returns the size in bytes. Alternatively, use pathlib.Path(path).stat().st_size for a modern approach.
📐

Syntax

There are two common ways to get a file size in Python:

  • os.path.getsize(path): Returns the size of the file at path in bytes.
  • pathlib.Path(path).stat().st_size: Uses the pathlib module to get file statistics, including size.
python
import os
from pathlib import Path

# Using os.path.getsize
size_bytes = os.path.getsize('example.txt')

# Using pathlib
size_bytes_pathlib = Path('example.txt').stat().st_size
💻

Example

This example shows how to get the size of a file named example.txt using both os.path.getsize and pathlib.Path.stat(). It prints the size in bytes.

python
import os
from pathlib import Path

file_path = 'example.txt'

# Create example file with some content
with open(file_path, 'w') as f:
    f.write('Hello, world!')

# Get size using os.path.getsize
size_os = os.path.getsize(file_path)
print(f"Size using os.path.getsize: {size_os} bytes")

# Get size using pathlib
size_pathlib = Path(file_path).stat().st_size
print(f"Size using pathlib: {size_pathlib} bytes")
Output
Size using os.path.getsize: 13 bytes Size using pathlib: 13 bytes
⚠️

Common Pitfalls

Common mistakes when getting file size include:

  • Using a wrong or non-existing file path, which causes FileNotFoundError.
  • Confusing file size with file content length (like string length).
  • Not handling exceptions when the file might not exist.

Always check if the file exists before getting its size or handle exceptions properly.

python
import os

file_path = 'missing.txt'

# Wrong way: no error handling
# size = os.path.getsize(file_path)  # This raises FileNotFoundError if file missing

# Right way: handle exception
try:
    size = os.path.getsize(file_path)
    print(f"File size: {size} bytes")
except FileNotFoundError:
    print(f"File '{file_path}' not found.")
Output
File 'missing.txt' not found.
📊

Quick Reference

Summary of methods to get file size in Python:

MethodDescriptionReturns
os.path.getsize(path)Get file size in bytes using os moduleInteger (bytes)
pathlib.Path(path).stat().st_sizeGet file size in bytes using pathlibInteger (bytes)

Key Takeaways

Use os.path.getsize(path) to get file size in bytes simply.
pathlib.Path(path).stat().st_size is a modern alternative to get file size.
Always handle exceptions or check if the file exists before getting size.
File size is returned in bytes, not characters or lines.
Both methods return the same result for the same file.