To check file size in Python, you don’t need complex tools—just a few lines of code can do the job. Ever wondered how big your files really are when working with Python? Knowing file size helps in managing storage, optimizing performance, and ensuring files meet upload or backup size limits.
Using os.path
# Python Program to Check the File Size Using os.path #importing os module import os file_size = os.path.getsize('d:/img1.jpg') print("File Size is :", file_size, "bytes")
Output:
File Size is : 218 bytes
Using stat() Function
# Python Program to Check the File Size Using stat() Function #importing os module import os file_size = os.stat('d:/image1.jpg') print("Size of file :", file_size.st_size, "bytes")
Output:
Size of file : 200 bytes
Python Program to Check the File Size Using file object
# Python Program to Check the File Size Using file object # open file file = open('d:/img.jpg') # get the cursor positioned at end file.seek(0, os.SEEK_END) # get the current position of cursor this will be equivalent to size of file print("Size of file is :", file.tell(), "bytes")
Output:
Size of file is : 220 bytes
Using pathlib
#Python Program to Check the File Size Using pathlib #importing pathlib module from pathlib import Path # open file Path(r'd:/image.jpg').stat() # getting file size file=Path(r'd:/image.jpg').stat().st_size # display the size of the file print("Size of file is :", file, "bytes")
Output:
Size of file is : 160 bytes
Bonus: Converting Bytes to KB, MB, or GB
When you check file size in Python, the result is usually in bytes. To make it more human-readable, you can convert it to kilobytes (KB), megabytes (MB), or gigabytes (GB). Below is a reusable helper function that does just that:
def convert_size(bytes_size): for unit in ['B', 'KB', 'MB', 'GB', 'TB']: if bytes_size < 1024: return f"{bytes_size:.2f} {unit}" bytes_size /= 1024
Example usage:
import os file_path = 'example.txt' size_in_bytes = os.path.getsize(file_path) readable_size = convert_size(size_in_bytes) print(f"File Size: {readable_size}")
This function helps present file sizes in a more understandable way, especially when displaying information to users or in logs.
Common Use Cases
1. Automating File Size Checks Before Uploads
When building apps or scripts that handle file uploads (like images, videos, or documents), it’s important to ensure the file size doesn’t exceed platform or API limits. Automatically rejecting oversized files improves efficiency and user experience.
import os def is_file_within_limit(file_path, max_size_mb): size = os.path.getsize(file_path) return size <= max_size_mb * 1024 * 1024
2. System Monitoring and Reporting
Track and log the size of files like server logs, backup files, or temp files. You can even automate cleanup scripts to delete or archive files exceeding a certain threshold.
import os log_file = 'server.log' if os.path.getsize(log_file) > 50 * 1024 * 1024: # 50 MB print("Warning: Log file size exceeded 50MB.")
3. Script Optimization
When working with large datasets or files, knowing their size can help you decide whether to load them fully into memory or process them in chunks, improving script performance.
file_size = os.path.getsize('data.csv') if file_size > 100 * 1024 * 1024: # 100 MB print("Consider processing this file in chunks.")
Interview or Practical Question Examples
Q1: How do you find the size of a file in Python?
Answer:
You can use os.path.getsize(file_path)
to get the file size in bytes. Alternatively, os.stat(file_path).st_size
or Path(file_path).stat().st_size
from the pathlib
module can be used for the same purpose.
import os size = os.path.getsize("example.txt") print(size) # Output in bytes
Q2: Compare different methods to check file size in Python.
Answer:
Here’s a comparison of three common methods:
Method | Module | Syntax | Notes |
---|---|---|---|
getsize() | os.path | os.path.getsize(file) | Simple and direct |
stat().st_size | os | os.stat(file).st_size | Provides detailed metadata |
Path().stat().st_size | pathlib | Path(file).stat().st_size | Pythonic and object-oriented (Python 3.4+) |
Use getsize()
for quick checks, stat()
when you need more file attributes, and pathlib
for cleaner, modern code.
To check file size in Python, you can use os.path.getsize()
, os.stat()
, or pathlib.Path.stat()
—each suited for different use cases. Choose the method that fits your coding style or additional file info needs. Try it out on your local system and explore more Python tutorials at Newtum. Happy coding!