Home > Enterprise >  Move a large list of files into a folder, and delete them from the original folder in R
Move a large list of files into a folder, and delete them from the original folder in R

Time:12-02

I am trying to move a large list of files to a newly created folder, and remove the files from the original folder. I will use some data that comes with base R as an example to hopefully make this easy to reproduce.

library(dplyr)

DNase %>% write.csv("movethis_1.csv")
mtcars %>% write.csv("movethis_2.csv")

files_to_move <- list.files(pattern = "movethis")

How would I move all members of files_to_move to a new folder, called folder_new, in my working directory, and remove them from the original folder? I have found how to do this with original files, but have had trouble applying it to a list. I tried doing the following:"

file.copy(from = paste0("MYDIRECTORYNAME", files_to_move),
          to = paste0("MYDIRECTORYNAME/folder_new", files_to_move))

However, the files did not move, and I got the following result:

[1] FALSE FALSE

CodePudding user response:

Using your example, here is the full workflow:

library(dplyr)

DNase %>% write.csv("movethis_1.csv")
mtcars %>% write.csv("movethis_2.csv")

files_to_move <- list.files(pattern = "movethis")

# Specify and create new directory
new_directory <- "other_path/different_folder/"
dir.create(new_directory, recursive = TRUE)

# Move files
fs::file_move(
  path = files_to_move,
  new_path = file.path(new_directory, basename(files_to_move))
)

All you would need to do is change the path in new_directory.

  • Related