Ever need to make sure a file not only exists in Python but also *contains* something before you proceed? It's a common task, and luckily, Python makes it straightforward. First, use `os.path.exists()` to verify the file's presence. But that's not enough! An empty file can still 'exist'.
Next, open the file in read mode ('r') and check its size. Here's a simple example:
```python
import os
def check_file(filepath):
if not os.path.exists(filepath):
return False, 'File does not exist.'
if os.stat(filepath).st_size == 0:
return False, 'File is empty.'
return True, 'File exists and has content.'
# Example usage:
file_path = 'my_file.txt'
exists, message = check_file(file_path)
print(message)
```
This code snippet first confirms existence, then uses `os.stat()` to get the file's size. If the size (`st_size`) is zero, the file's empty. This combination ensures you're working with a valid and populated file, preventing potential errors down the line. Remember to handle file paths correctly to avoid common pitfalls!