5+ Easy Ways to Check if File is Empty in Python[with Code Examples] - JSON Viewer

5+ Easy Ways to Check if File is Empty in Python[with Code Examples]

In addition to file operations, Python is a well-liked programming language that is utilised for a range of activities. We frequently need to determine whether a file is empty or not while working with files in Python.

Since an empty file is empty of any data, it has a size of 0. For a number of reasons, including preventing mistakes when reading data from a file or confirming that a file has the intended information, it can be useful to check if a file is empty.

This article will examine various Python-based techniques for determining whether a file is empty. Both the internal functions and the third-party libraries that can be used for this will be covered.

Different Ways to Check if File is Empty in Python

Method 1: Use os.path.getsize(file_path) function

import os
def is_file_empty(file_path):
    return os.path.getsize(file_path) == 0

The is file empty function, which is defined in this code, accepts a file path as an input and returns a Boolean value indicating whether or not the file is empty.

The os.path.getsize() function is used within the function to determine the file’s size in bytes. The function will return True, indicating that the file is empty, if the file’s size is 0. The function will return False, indicating that the file is not empty, if the size of the file is larger than 0.

The file path can be sent as an input to this function to determine whether a single file is empty. If the file is empty, for instance, is file empty(“/path/to/file.txt”) will return Yes; otherwise, it will return False.

If you need to check that several files in your application are empty, defining a function like this might be helpful since you can call the function with each file path rather than having to repeat the same code over and over.

Method 2: Use the pathlib module to see if a file is empty

from pathlib import Path
file_path = Path('/path/to/file.txt')
if file_path.stat().st_size == 0:
    print(f"{file_path} is empty")

The pathlib module is used in this code to determine whether a file is empty.

Initially, a Path object representing the file at “/path/to/file.txt” is created using the Path() function. It is simple and platform-independent to work with file paths using the Path() method.

To obtain information about the file’s state, the stat() method is then invoked on the Path object. The stat() result’s st_size field is then examined to see if it equals zero.

The code block will be executed and a message stating that the file is empty will be printed if the file is empty because st_size will be zero in that case.

The if statement will evaluate to False and the code block will be skipped if the file is not empty since st_size will be bigger than zero.

Essentially, this code uses the pathlib module to check if a file is empty in a platform-independent manner. It’s important to note that this approach is quick and doesn’t call for reading the whole file into memory.

Method 3: Check if a file is empty using file.readlines()

with open('/path/to/file.txt', 'r') as f:
    if not f.readlines():
        print("The file is empty")
    else:
        print("The file is not empty")

The mode “r,” which stands for reading, is used to open the file “file.txt” at the path “/path/to/”. Then, using the if not f.readlines(): command, it determines if the file is empty.

A line from the file is represented by each string in the list of strings returned by the f.readlines() method, which reads the file’s contents.

Python considers an empty list returned by f.readlines() as False if the file is empty. So, if f.readlines() returns False, the code block after the if expression will be run and the message “The file is empty” will be printed.

If the file is not empty, the function f.readlines() will return a list of strings that represent the file’s lines. In Python, this list is regarded as True. As a result, if f.readlines() returns False, the else statement’s code block, which prints “The file is not empty,” will be executed.

f.readlines() reads the full file into memory and produces a list, which can be inefficient for large files. Using f.read(), as seen in the preceding example, is a more effective strategy if all you need to do is determine whether a file is empty.

To acquire a list of filenames in the directory at “/path/to/directory,” use the os.listdir() function. Following that, a for loop loops through each filename in the directory.

The os.path.join() function is used to build the complete path to each filename. The directory path and the filename are joined using the os.path.join() function to provide a platform-independent file path.

The path is then checked to see if it points to a regular file using the os.path.isfile() function (as opposed to a directory, symlink, or other type of file). The size of the file in bytes can be obtained using the os.path.getsize() function.

The if statement will evaluate to True and the code block will be performed, printing a message indicating that the file is empty if the file is empty (that is, if its size is 0).

The if statement will evaluate to False if the file is not empty (that is, if its size is larger than 0), in which case the code block will not be executed.

Overall, using this code to check for empty files in a directory is effective. It’s important to note that this method is quicker than some others because it merely measures each file’s size and doesn’t read the complete file into memory.

Method 4: Check if a file is empty using file.read()

with open('/path/to/file.txt', 'r') as f:
if not f.read():
print("The file is empty")
else:
print("The file is not empty")

This code opens a file named “file.txt” located at the path “/path/to/”, with the mode “r” which stands for reading. Then, using the if not f.read(): statement, it determines if the file is empty.

The file’s contents are read by the f.read() method, which returns the contents as a string. Python considers an empty string returned by f.read() as False if the file is empty. As a result, the code block following the if statement will be run, printing “The file is empty” when not f.read() returns True.

If the file is not empty, f.read() will return a string containing the file contents, which is considered True in Python. Therefore, not f.read() will be False, and the code block under the else statement will be executed, which prints “The file is not empty”.

Python: Check if a directory has any empty files

To determine whether a directory includes any empty files, this code makes use of the OS module.

import os
dir_path = '/path/to/directory'
for filename in os.listdir(dir_path):
    filepath = os.path.join(dir_path, filename)
    if os.path.isfile(filepath) and os.path.getsize(filepath) == 0:
        print(f"{filepath} is empty")

Python: Check if several files are empty.

import os
file_paths = ['/path/to/file1.txt', '/path/to/file2.txt', '/path/to/file3.txt']
for file_path in file_paths:
    if os.path.getsize(file_path) == 0:
        print(f"{file_path} is empty")
    else:
        print(f"{file_path} is not empty")

To determine whether numerous files are empty, this code employs a loop.

The file paths variable is used to define a list of file paths first. The paths to three files are “/path/to/file1.txt,” “/path/to/file2.txt,” and “/path/to/file3.txt,” respectively.

The next step is to cycle through each file path in the file paths list using a for loop. The os.path.getsize() function is used to obtain the file size in bytes for each file path.

The if statement will evaluate to True and the code block will be performed, printing a message indicating that the file is empty if the file is empty (that is, if its size is 0).

The if statement will evaluate to False if the file is not empty (that is, if its size is larger than 0), in which case the code block will not be executed. The else block, which prints a message indicating that the file is not empty, will be executed in its place.

In general, using this code is an easy way to determine whether a number of files are empty. To examine the size of a file, this method reads the full file into memory, which may be inefficient for large files.

Conclusion

It’s crucial to determine whether a file in Python is empty. There are various approaches to doing this, ranging from easy to difficult ones. You can effectively determine whether or not a file is empty by choosing the appropriate approach.