0

I will have list of source path & destination path in excel,

How can I move these files

source destination
C:/users/desk/1/a.pdf C:/users/desktop/2
C:/users/desk/1/b.pdf C:/users/desktop/3
C:/users/desk/1/abb.pdf C:/users/desktop/56

I need to copy a file from particular source to respective given destination.

user438383
  • 5,716
  • 8
  • 28
  • 43

1 Answers1

1

To copy the files, you can use file.copy. This accepts a vector of single directory, or a vector of file paths as destinations, and copies the files to the new directory/paths.

As your destination column contains only directory paths, you need to specify full paths (including file names) for new files. To do this, you can use file.path and basename to concatenate the original file names (in source) to the new directories (destination).

df = data.frame(
  source = c('C:/users/desk/1/a.pdf', 'C:/users/desk/1/b.pdf', 'C:/users/desk/1/abb.pdf'),
  destination = c('C:/users/desktop/2', 'C:/users/desktop/3', 'C:/users/desktop/56')
)
file.copy(from = df$source, to = file.path(df$destination, basename(df$source)))

To move the files, you can use file.rename.

file.rename(from = df$source, to = file.path(df$destination, basename(df$source)))

Note 1: file.rename may only work when moving files between locations on the same drive. To move files across drives you could use file.copy followed by file.remove to remove the original files after copying. If doing this, you should be careful not to remove files if the copy operation fails, e.g.:

file.move <- function(from, to, ...) {
  # copy files and store vector of success
  cp <- file.copy(from = from, to = to, ...)

  # remove those files that were successful
  file.remove(from[cp])

  # warn about unsuccessful files
  if (any(!cp)) {
    warning(
      'The following files could not be moved:\n', 
      paste(from[!cp], collapse = '\n')
    )
  }
}

file.move(from = df$source, to = file.path(df$destination, basename(df$source)))

Note 2: This is all assuming that you have read in your excel data using one of read.csv or data.table::fread (for .csv files) or readxl::read_excel (for .xls or .xlsx files)

sjt
  • 61
  • 4
  • This code is not working, multiple files not moving/copying, getting false at end of the output – Hemachand Srinivasan Mar 25 '22 at 08:41
  • @HemachandSrinivasan Apologies, apparently `file.copy` only accepts a single directory, or a vector of complete paths. I have amended my answer to reflect this. – sjt Mar 25 '22 at 10:21