Determine whether a file is empty in Python
This post will discuss how to determine whether a file is empty in Python.
You can easily check for an empty file in Python by finding the size of the file, which should be 0 bytes. There are several ways to do that:
1. Using os module
The os.stat() function returns a stat_result object, whose st_size attribute stores the size of the file, in bytes.
|
1 2 3 4 5 |
import os isempty = os.stat('path\to\file\filename.ext').st_size == 0 print(isempty) |
Alternatively, you can use the os.path.getsize() function to get the specified file size in bytes.
|
1 2 3 4 5 6 7 |
import os size = os.path.getsize('path\to\file\filename.ext') isempty = size == 0 print(isempty) |
2. Using pathlib module
With Python 3.4, you can use the pathlib.Path.stat() function, which returns the stat_result object containing information about the specified path, similar to the os.stat() function.
|
1 2 3 4 5 6 7 |
from pathlib import Path path = Path('path\to\file\filename.ext') isempty = path.stat().st_size == 0 print(isempty) |
3. Using File object
Another option is to open the file in reading mode using the built-in function open() and set the current position of the file descriptor at the end with the seek() function. Then you can use the tell() function to get the current position of the cursor in bytes.
|
1 2 3 4 5 6 7 8 |
import os with open('path\to\file\filename.ext', 'r') as file: file.seek(0, os.SEEK_END) isempty = file.tell() == 0 file.seek(0) # rewind the file print(isempty) |
That’s all about determining whether a file is empty 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 :)