Get size of a file in Python
This post will discuss how to get the size of a file in Python.
1. Using os.stat() function
The standard solution to get a file’s status is using the os.stat() Python function. It returns a stat_result object, which has a st_size attribute containing the file’s size in bytes.
|
1 2 3 4 5 |
import os stats = os.stat('path\to\file\filename.ext') print(stats.st_size) |
2. Using Path.stat() function
Alternatively with Python 3.4, you can use the Path.stat() function from pathlib module. It is similar to the os.stat() function and returns stat_result object containing information about the specified path.
|
1 2 3 4 5 6 |
from pathlib import Path f = Path('path\to\file\filename.ext') size = f.stat().st_size print(size) |
3. Using os.path.getsize() function
Another good option is to use the os.path.getsize() function to get the size of the specified path in bytes.
|
1 2 3 4 5 |
import os size = os.path.getsize('path\to\file\filename.ext') print(size) |
4. Using seek() function
Here, the idea is to open the file in read-only mode and set the current position of the file descriptor at the end. This can be done using the seek() function, which returns the current cursor position in bytes, starting from the beginning.
|
1 2 3 4 5 6 |
import os with open('path\to\file\filename.ext', 'r') as f: size = f.seek(0, os.SEEK_END) print(size) |
That’s all about getting the size of a file in Python.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)