I have thousands of text files and would like to know how to check if a particular file is empty. I am reading all the files using this line of code
Y<-grep("*.txt", list.files(), value = TRUE)
I would like a list of names of all the blank files. Have to do it in R.
Thanks.
If your file was truly empty, with ls -l (or dir on windows) reporting a size of 0, os. path. getsize() should also return 0.
Delete Empty Files in a Directory In order to delete empty files, we need to perform two steps. First, search all the empty files in the given directory and then, delete all those files. This particular part of the command, find . -type f -empty -print, will find all the empty files in the given directory recursively.
The above code works in a simple manner: peek() will peek at the stream and return, without removing, the next character. If it reaches the end of file, it returns eof() . Ergo, we just peek() at the stream and see if it's eof() , since an empty file has nothing to peek at.
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
!
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())
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With