Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I check if a file is empty?

Tags:

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.

like image 447
Geekuna Matata Avatar asked Apr 23 '14 19:04

Geekuna Matata


People also ask

How do you check if a file is empty in Python?

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.

How do I find empty files in a folder?

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.

How check if file is empty C++?

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.


2 Answers

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!

like image 132
Konrad Rudolph Avatar answered Oct 17 '22 06:10

Konrad Rudolph


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())
like image 28
Neal Fultz Avatar answered Oct 17 '22 08:10

Neal Fultz