Checking If a File is Empty in R

To check if a file is empty in R, you can use either the “file.info()’s size attribute” or the “file.size()” function.

Comparing methods

We must check if a file is empty to save our resources from reading or processing. It helps us put a data validation that will prevent unexpected results or errors. Based on its emptiness, we can make an informed decision.

In my current working directory, I have two files:

  1. empty.txt
  2. data.txt

As the name suggests, empty.txt is an empty file, and data.txt contains some data.

Screenshot of empty and non-empty files

Method 1: Using file.info()

The file.info() is a built-in R function that retrieves information about the file, including size, permission, modification, time, and other metadata.

The file.info() function returns a file object containing various information, and one is the “size” attribute. The $size attribute suggests the file size in bytes. If $size is 0, the file is empty.

Let’s check for an empty.txt file:

# Getting file object
file_info <- file.info("empty.txt")

# Checking if the file is empty by comparing its size to 0
if (file_info$size == 0) {
  cat("The file is empty.\n")
} else {
  cat("The file is not empty.\n")
}

Output

The file is empty.

As expected, since we knew that the file was empty, it gave the correct result.

Let’s check for data.txt file:

# Getting file object
file_info <- file.info("output/data.txt")

# Checking if the file is empty by comparing its size to 0
if (file_info$size == 0) {
  cat("The file is empty.\n")
} else {
  cat("The file is not empty.\n")
}

Output

The file is not empty.

If you want to check file size as well as other metadata of the file, I highly recommend you use this approach. However, it might be less concise if you only care about checking emptiness because, for that, there is an easy way.

Method 2: Using file.size()

The file.size() is the simplest way because it returns the file size in bytes directly. If the size is 0, it means the file is empty; otherwise, it is not an empty file.

Let’s check for an empty.txt file:

file_path <- "empty.txt"

# Checking if the file is empty by comparing its size to 0
if (file.size(file_path) == 0) {
  cat("The file is empty.\n")
} else {
  cat("The file is not empty.\n")
}

Output

The file is empty.

Let’s check for a data.txt file:

file_path <- "output/data.txt"

# Checking if the file is empty by comparing its size to 0
if (file.size(file_path) == 0) {
  cat("The file is empty.\n")
} else {
  cat("The file is not empty.\n")
}

Output

The file is not empty.

If your goal is solely to find whether the file is empty or not, use the .size() approach. This approach does not give more information about the file’s metadata.

Leave a Comment