4

I am writing code using R that invokes Linux commands to create a directory with multiple files which has to be deleted at the end.

I tried using file.remove(directory_name) which removed the directory only when its empty. If the directory has files, file.remove didn’t work. unlink(directory_name) didn't remove the directory.

My code:

dir.create("./dir1")  
dir.create("./dir2")  
............  
............  
............  
file.remove("./dir1")  
unlink("./dir1, recursive = TRUE")  

file.remove() threw an error:

cannot remove file './dir1', reason 'Directory not empty'.

while, unlink() didn't remove the directory.

How do I delete a directory with files in it?

Stephen Rauch
  • 47,830
  • 31
  • 106
  • 135
amc794
  • 65
  • 6

1 Answers1

0

To unlink recursively, you need to pass the recursive = TRUE as an additional parameter:

This:

 unlink("./dir1", recursive = TRUE)  

Not this:

unlink("./dir1, recursive = TRUE")  
Stephen Rauch
  • 47,830
  • 31
  • 106
  • 135