How do I check file size in Python?
To check file size using Python's built-in os.path.getsize() function:
Before using that, ensure the file exists to avoid errors:
Exploring alternative approaches
If you find yourself in Python 3.4 or later, you have a modern alternative at your disposal: the pathlib module:
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():
When dealing with file-like objects, we can use tell() and seek() to sneakily get the file 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:
Efficient file path handling
pathlib can streamline your code when dealing with file paths:
pathlib also allows for elegant path definitions, no more messing around with string concatenation:
Packaging file size retrieval
To make your life easier, organize the file size retrieval logic into a function:
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.
Was this article helpful?