0

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.

Alex
  • 15,186
  • 15
  • 73
  • 127

1 Answers1

2

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")
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213
  • is there a way for the function to determine whether it is a directory or file being passed automatically? – Alex Oct 02 '19 at 04:45
  • ah I suppose I could use: https://stackoverflow.com/questions/46147901/r-test-if-a-file-exists-and-is-not-a-directory thanks – Alex Oct 02 '19 at 04:46
  • @Alex yes you can use that but ideally it is better to standardize the inputs. If you look at `file.copy` it accepts complete path **only** and not folder and path both. – Ronak Shah Oct 02 '19 at 04:53
  • I don't see that "file.copy it accepts complete path only..." – Alex Oct 02 '19 at 05:39