Sometimes, we want to check whether a file is empty or not with Python.
In this article, we’ll look at how to check whether a file is empty or not with Python.
How to check whether a file is empty or not with Python?
To check whether a file is empty or not with Python, we can use the os.stat
method.
For instance, we write
import os
is_empty = os.stat("file.txt").st_size == 0
to get the size of file.txt with os.stat
.
We get the size in bytes with st_size
.
And if it’s 0, then the file is empty.
Conclusion
To check whether a file is empty or not with Python, we can use the os.stat
method.