Skip to main content

How to check if a file is empty in Python

How to check if a file is empty in Python.

Here's a step-by-step tutorial on how to check if a file is empty in Python:

Step 1: Open the File

To check if a file is empty, we need to first open it. We can use the open() function in Python to open the file. The open() function takes two parameters: the file path and the mode in which the file should be opened. In this case, we'll use the mode 'r' to open the file in read-only mode.

file_path = 'path/to/file.txt'
file = open(file_path, 'r')

Step 2: Read the File

Once the file is opened, we can read its contents. We'll use the read() method to read the entire file into a string.

file_contents = file.read()

Step 3: Check if the File is Empty

To check if a file is empty, we can simply check if the length of the file contents is equal to zero. If it is, then the file is empty.

if len(file_contents) == 0:
print("File is empty!")
else:
print("File is not empty.")

Step 4: Close the File

After performing the necessary operations on the file, it's important to close it. This is done using the close() method.

file.close()

Complete Example

Putting it all together, here's a complete example that checks if a file is empty:

file_path = 'path/to/file.txt'
file = open(file_path, 'r')
file_contents = file.read()

if len(file_contents) == 0:
print("File is empty!")
else:
print("File is not empty.")

file.close()

Alternative Approach: Using the file size

Instead of reading the entire file contents, we can also check the file size to determine if it's empty. The file size can be obtained using the os.path.getsize() function from the os module.

import os

file_path = 'path/to/file.txt'
file_size = os.path.getsize(file_path)

if file_size == 0:
print("File is empty!")
else:
print("File is not empty.")

This approach can be more efficient for large files, as it avoids reading the entire file into memory.

That's it! You now know how to check if a file is empty in Python.