Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

[1] FALSE FALSE

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading