How do I check if a file is empty in Python?
Antek N
antek n profile pic

In Python, you can check if a file is empty using different approaches. Here's a detailed explanation of a few commonly used methods: Using the os module: Theos module provides thepath.getsize() function, which returns the size of a file in bytes. You can use this function to check if the size of the file is zero, indicating an empty file.

1
2
3
4
5
6
7
8
9

import os

file_path = 'path/to/file.txt'

if os.path.getsize(file_path) == 0:
    print("File is empty.")
else:
    print("File is not empty.")

In this example,os.path.getsize(file_path) retrieves the size of the file specified byfile_path, and the returned size is compared to zero. If the size is zero, the file is considered empty, and the corresponding message is printed. Using the file object: You can also check if a file is empty by opening it using a file object and using theread() method to read its contents. If theread() method returns an empty string, it means the file is empty.

1
2
3
4
5
6
7
8

file_path = 'path/to/file.txt'

with open(file_path, 'r') as file:
    if file.read() == '':
   print("File is empty.")
    else:
   print("File is not empty.")

In this example, thewith statement is used to open the file in read mode and automatically close it when the block is exited. Theread() method is then called on the file object to read its contents. If the returned value is an empty string, the file is considered empty. Using the os.stat() function: Theos.stat() function provides file status information, including the file size. You can use it to retrieve the size of the file and check if it is zero.

1
2
3
4
5
6
7
8
9
10
11

import os

file_path = 'path/to/file.txt'

file_stat = os.stat(file_path)

if file_stat.st_size == 0:
    print("File is empty.")
else:
    print("File is not empty.")

In this example,os.stat(file_path) retrieves the file status information for the file specified byfile_path, andfile_stat.st_size retrieves the size of the file. If the size is zero, the file is considered empty. It's important to note that these methods only check if the file is empty in terms of its size. If the file contains whitespace characters or special characters, it won't be considered empty based on these size-based checks. Choose the method that best suits your needs based on the specific requirements of your program.