Methods to Check If a File is Empty
Now that we have our test files, let's explore different Python methods to check if a file is empty. We'll create a Python script to demonstrate each approach.
Create a new file named check_empty.py
in your project directory by following these steps:
- In the WebIDE, click on the "New File" icon in the Explorer panel
- Name the file
check_empty.py
and save it in the ~/project
directory
- Copy the code from each method as we go through them
Method 1: Using os.path.getsize()
The most straightforward way to check if a file is empty is to use the os.path.getsize()
function from the os
module. This function returns the size of a file in bytes. If the file is empty, it returns 0
.
Add the following code to your check_empty.py
file:
import os
def check_empty_using_getsize(file_path):
"""Check if a file is empty using os.path.getsize()"""
try:
if os.path.getsize(file_path) == 0:
return True
else:
return False
except OSError as e:
print(f"Error checking file: {e}")
return None
## Test with our files
empty_file = "/home/labex/project/empty_file.txt"
non_empty_file = "/home/labex/project/non_empty_file.txt"
print(f"Method 1: Using os.path.getsize()")
print(f"Is {empty_file} empty? {check_empty_using_getsize(empty_file)}")
print(f"Is {non_empty_file} empty? {check_empty_using_getsize(non_empty_file)}")
print()
Method 2: Using File Read Method
Another approach is to open the file, read its contents, and check if anything was read. If the file is empty, reading it will return an empty string.
Add the following code to your check_empty.py
file:
def check_empty_using_read(file_path):
"""Check if a file is empty by reading it"""
try:
with open(file_path, 'r') as file:
content = file.read()
if len(content) == 0:
return True
else:
return False
except IOError as e:
print(f"Error reading file: {e}")
return None
print(f"Method 2: Using file.read()")
print(f"Is {empty_file} empty? {check_empty_using_read(empty_file)}")
print(f"Is {non_empty_file} empty? {check_empty_using_read(non_empty_file)}")
print()
Method 3: Using os.stat()
The os.stat()
function provides detailed information about a file, including its size. You can check the st_size
attribute to determine if the file is empty.
Add the following code to your check_empty.py
file:
def check_empty_using_stat(file_path):
"""Check if a file is empty using os.stat()"""
try:
file_stats = os.stat(file_path)
if file_stats.st_size == 0:
return True
else:
return False
except OSError as e:
print(f"Error getting file stats: {e}")
return None
print(f"Method 3: Using os.stat()")
print(f"Is {empty_file} empty? {check_empty_using_stat(empty_file)}")
print(f"Is {non_empty_file} empty? {check_empty_using_stat(non_empty_file)}")
print()
Method 4: Using the pathlib Module
Python's pathlib
module provides an object-oriented approach to working with file paths. We can use it to check if a file is empty as well.
Add the following code to your check_empty.py
file:
from pathlib import Path
def check_empty_using_pathlib(file_path):
"""Check if a file is empty using pathlib.Path"""
try:
path = Path(file_path)
if path.stat().st_size == 0:
return True
else:
return False
except OSError as e:
print(f"Error checking file with pathlib: {e}")
return None
print(f"Method 4: Using pathlib")
print(f"Is {empty_file} empty? {check_empty_using_pathlib(empty_file)}")
print(f"Is {non_empty_file} empty? {check_empty_using_pathlib(non_empty_file)}")
Running the Script
Now let's run our script to see all methods in action. In the terminal, execute:
python3 ~/project/check_empty.py
You should see output similar to this:
Method 1: Using os.path.getsize()
Is /home/labex/project/empty_file.txt empty? True
Is /home/labex/project/non_empty_file.txt empty? False
Method 2: Using file.read()
Is /home/labex/project/empty_file.txt empty? True
Is /home/labex/project/non_empty_file.txt empty? False
Method 3: Using os.stat()
Is /home/labex/project/empty_file.txt empty? True
Is /home/labex/project/non_empty_file.txt empty? False
Method 4: Using pathlib
Is /home/labex/project/empty_file.txt empty? True
Is /home/labex/project/non_empty_file.txt empty? False
As you can see, all four methods correctly identify our empty and non-empty files. In the next step, we'll create a practical script that uses these methods for file management.