Reputation: 8019
I am on the lookout for an efficient way to delete all empty files in a directory & subdirectories in R - what would be the best way forward? (I have directories with 100 000s of files, so it would have to be fast)
Upvotes: 2
Views: 2841
Reputation: 7174
I was trying to remove empty .txt
-files from a directory, for which the size of an "empty" .txt
-file is 1, instead of 0. In order to remove those files I used essentially the same approach as Josh O'Brien, but a bit simpler:
# All document names:
docs <- list.files(pattern = "*.txt")
# Use file.size() immediate, instead of file.info(docs)$size:
inds <- file.size(docs) == 1
# Remove all documents with file.size = 1 from the directory
file.remove(docs[inds])
Upvotes: 2
Reputation: 162461
## Reproducible example, with two empty and one non-empty files
dir.create("A/B/C", recursive=TRUE)
dir.create("A/D", recursive=TRUE)
cat("", file="A/B/C/empty1.txt")
cat("", file="A/empty2.txt")
cat("111", file="A/D/notempty.txt")
## Get vector of all file names
ff <- dir("A", recursive=TRUE, full.names=TRUE)
## Extract vector of empty files' names
eff <- ff[file.info(ff)[["size"]]==0]
## Remove empty files
unlink(eff, recursive=TRUE, force=FALSE)
## Check that it worked
dir("A", recursive=TRUE, full.names=TRUE)
# [1] "A/D/notempty.txt"
Upvotes: 3