Get file size using python

In this article, we shall see how to get file size with python using built-in libraries. The os module and the pathlib module in python can be used to find the size of a file. This blog post deals with the following three ways to find the file size using python.

All these methods will return the file size in bytes only. Let us look at the different methods one by one with an example for each.

Using os module and path class

import os

size = os.path.getsize('sample.pdf')
print(size)

The output of the above code is

3028

Which is nothing but the file size in bytes.

Using os module and stat method

import os

size = os.stat('sample.pdf').st_size
print(size)

The output of this code is also the file size in bytes.

3028

Using Path class from the pathlib module

The next method is using the Path class from the pathlib module. This class will return an object, from which the file size can be obtained using the stat() method.

import os
from pathlib import Path

size = Path('sample.pdf').stat().st_size
print(size)

The output of this code is

3028

Conclusion

Hope this article is helpful. If you have any queries leave them in the comments skeleton. I will try to answer them as soon as possible.

Happy coding!