Tom Wenseleers Tom Wenseleers - 3 days ago 4
R Question

R: efficiently delete all empty files in a directory

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)

Answer
## 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"
Comments