Alex
Alex

Reputation: 15708

File copy, making directories as necessary

Similar to https://stackoverflow.com/a/10268255/, I would like a function that automatically makes sub-directories where they don't exist, when file.copy is used. Current I am getting the error:

In file.copy( ... :
  'recursive' will be ignored as 'to' is not a single existing directory

Unfortunately using a function like:

my.file.copy<- function(from, to, ...) {
    todir <- dirname(to)
    if (!isTRUE(file.info(todir)$isdir)) dir.create(todir, recursive=TRUE)
    file.copy(from = from,  to = to, ...)
}

does not work as dirname strips the last subdirectory if to is a directory.

Upvotes: 1

Views: 489

Answers (1)

Ronak Shah
Ronak Shah

Reputation: 388962

Depending on how you are going to pass to parameter to the function, we can use one of these.

1) If you are going to pass to with only directory name and expect it to take filename from from argument, we can use the below function

my.file.copy_dir <- function(from, to, ...) {
   if (!dir.exists(to))  dir.create(to, recursive = TRUE) 
   file.copy(from = from,  to = paste0(to, basename(from)), ...)
}

2) If you are going to pass to as complete path to new file name we can use

my.file.copy_file <- function(from, to, ...) {
   if (!dir.exists(dirname(to)))  dir.create(dirname(to), recursive = TRUE) 
   file.copy(from = from,  to = to, ...)
}

and use them as :

my.file.copy_dir("/path/of/file/report.pdf", "/new/path/of/file/")

and

my.file.copy_file("/path/of/file/report.pdf", "/new/path/of/file/abc.pdf")

Upvotes: 3

Related Questions