Home > Software design >  R copy one file to all subdirectories
R copy one file to all subdirectories

Time:09-28

I'm working on an R script where I create multiple sub-folders according to some parameters. After everything I have to do I then have to copy one file into all of these new sub-folders.

Is there a way in R to do this easily? I would like to avoid for loops if I can. I've read about file.copy but that doesn't seem to do the trick (from what I've read, it works the opposite way: it copies everything from a folder -including subfolders and their contents if recursive=TRUE- to a new folder, whereas I want one specific file copied to all subdirectories of a folder)

I've seen questions like Copy files from folders and sub-folders to another folder and saving the structure of the folders, How to copy specific file from sub-folder to another Folder in R? or Copy folder recursive in R but that's just the opposite direction of what I want.

CodePudding user response:

file.copy() has vectorized from and to arguments. If you have a vector of directories you want to copy the file to you can simply do:

filename <- "my_file.txt"

to_directories <- c("dir 1", "dir 2", "dir 3")

file.copy(filename, file.path(to_directories, filename))

[1] TRUE TRUE TRUE
  • Related