Explain Codes LogoExplain Codes Logo

How do I check file size in Python?

python
file-size
pathlib
file-handling
Nikita BarsukovbyNikita Barsukov·Aug 13, 2024
TLDR

To check file size using Python's built-in os.path.getsize() function:

import os print(os.path.getsize('example.txt'), 'bytes') # print file size in bytes

Before using that, ensure the file exists to avoid errors:

if os.path.isfile('example.txt'): print(os.path.getsize('example.txt'), 'bytes') # File exists, print its size in bytes else: print('File not found. Maybe it went on a vacation.') # Oops, file is not found

Exploring alternative approaches

If you find yourself in Python 3.4 or later, you have a modern alternative at your disposal: the pathlib module:

from pathlib import Path print(Path('example.txt').stat().st_size, 'bytes') # Let pathlib do the heavy lifting

Here, stat() method returns an os.stat_result object with a buffet of file attributes, 'st_size' indicates the file size in bytes.

For those playing in hard mode where the files content cannot be read, yet you still need the size, Python offers os.stat():

print(os.stat('example.txt').st_size, "bytes") # Who needs file content anyway?

When dealing with file-like objects, we can use tell() and seek() to sneakily get the file size:

with open('example.txt', 'rb') as f: f.seek(0, os.SEEK_END) # Run to the end of the file size = f.tell() # Now tell me what you've got print(size, 'bytes') # Voila! There's the size.

Don't forget to reset the file pointer when you're done playing hide and seek with it.

Making file size human-friendly

Staring at a file size in bytes is like eating soup with a fork. So, let's use this helper function to get a file size in a readable form:

def convert_bytes(num): for unit in ['bytes', 'KB', 'MB', 'GB', 'TB']: if num < 1024: return "%3.1f %s" % (num, unit) num /= 1024 # Divide and conquer print(convert_bytes(Path('example.txt').stat().st_size)) # Ah, much better!

Efficient file path handling

pathlib can streamline your code when dealing with file paths:

file_size = Path('/path/to/file').stat().st_size # Guess who's back? Back again! print(file_size, 'bytes')

pathlib also allows for elegant path definitions, no more messing around with string concatenation:

file_path = Path('/path/to') / 'file' # No more "/'" + 'filename' concatenation mess print(file_path.stat().st_size, 'bytes') # Back to bytes!

Packaging file size retrieval

To make your life easier, organize the file size retrieval logic into a function:

def file_size(filepath: str) -> int: return Path(filepath).stat().st_size # Encapsulating file size retrieval print(file_size('example.txt'), 'bytes') # Now we're talking!

Special considerations

There might be cases where read permissions are restricted. In such scenarios, os.stat() comes to your aid over seek() and tell(). So remember to understand the operating system's file permissions while partying with files.