How can I check if a file is empty?

For a functional approach, you might first write a predicate:

file.empty <- function(filenames) file.info(filenames)$size == 0

And then filter the list of files using it:

Filter(file.empty, dir())

You can use file.size:

empty = filenames[file.size(filenames) == 0L]

file.size is a shortcut for file.info:

info = file.info(filenames)
empty = rownames(info[info$size == 0L, ])

Incidentally, there’s a better way of listing text files than using grep: specify the pattern argument to list.files:

list.files(pattern = '\\.txt$')

Note that the pattern needs to be a regular expression, not a glob — and the same is true for grep!


Use the following code to check if a file in the system is empty or not before uploading it.

my_file<-readLines(paste0("<path of file/file name.extension>"))
my_file=="" #TRUE - means the file is empty

Tags:

R