How To Check File Size In Python In Bytes

In this article, we will learn how to check the file size using Python code. So to begin with, we will first look at some of the functions that we can use to do so. But we will not just stop there. Instead, we will look at some example code as well.

So does that sound good for you? Yeah? Great! So then let us start right away!

Check File Size In Python Using OS Module

If you look at Python’s OS module, you will see that it’s path sub module has a getsize( ) function. So we can use this function to to check the size of a file!

So how does the code using this function look like? Take a look at it for yourself!

import os
file_path = 'hello.txt'

So as you can see in the above code, we are calling the getsize( ) function with the file_path parameter. Now this is a parameter that has the file name along with it’s path.

Check File Size In Python
Check File Size In Python

In our case, we are accessing a file called hello.txt which is in the same directory as from where this Python code is run. So we did not have to give any folder name. But if your file lies in some other folder, then we need to give it’s full path.

Does that make sense? Great! So then how does the output look like? Well take a look at it yourself:


So is it just a number? Well yeah! But that is the number of bytes present in that file. Got it?! So, what it means is that the size of our file hello.txt is 766 bytes!

So it is quite easy to use the getsize( ) function then. Right?

But what happens if the file does not exist? Well, it just raises the os.error in that case!

Sounds good? Great! But this is not the only way for us to check the file size in Python. Alright? Here is another way to do it!

Check File Size Using OS Stat Module

So here is yet another way for us to check the file size – by making use of the OS stat module.

In this case, we will make use of the st_size member value of the os.stat module. This value is nothing but the size of a file. Alright? So then how does it’s code look like? Well, take a look at it here:

import os
filepath = 'hello.txt'

The output that we get here is once again:


Same as the previous example code’s value. Right?


So there you have it. Those are the simplest ways by which we can check the file size in Python. Working with files in Python is easy when we make use of built in modules. The OS module is one such module that will make our life easier.

So with this, I will end this article now. We will continue to look at some more Python modules in the future. But for now, I guess this should do it. Right? But if you have any queries on this, do let me know and I will be happy to help.

So until next time. Take care!

Want to know what are Python Reserved Keywords? Check this out!