Categories
Python Answers

How to check whether a file is empty or not with Python?

Spread the love

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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *