Am I missing something in the functions?
I want to copy a folder with some files and another subfolder from one location to another. I tried to use file.copy(from, to, recursive=TRUE)
but it complains with an error message:
In file.copy("my_folder", "new_folder", :
'recursive' will be ignored as 'to' is not a single existing directory
The result is a file called new_folder
with no content.
Is there a way to copy the complete folder structure with R?
In order to copy the content of a directory recursively, you have to use the “cp” command with the “-R” option and specify the source directory followed by a wildcard character.
copy() function as shown in the following R syntax. Within the file. copy function, we have to specify the directory path and file names of the first folder from which we want to copy the files, as well as the directory path and file names of the second folder to which we want to copy the files.
Recursive means that cp copies the contents of directories, and if a directory has subdirectories they are copied (recursively) too. Without -R , the cp command skips directories.
The -r flag tells the file system to recursively roll down the file/directory tree and copy any & all contents that might be a “child” of that file to a new place.
Ok, I just figured out what the error means... :-) I have to create the new directory in advance and now I can copy everything...
dir.create('new_folder')
file.copy("my_folder", "new_folder", recursive=TRUE)
This works as expected.
I think R.utils::copyDirectory(oldDir, newDir)
is the solution to what you're asking. It doesn't require creating newDir
first, either.
as @matifou says in the comments, the accepted answer by the questioneer himself is a bit confusing, because you end up with the copied folder inside a folder with the same name as the copied folder... to avoid this, do this instead:
case: you want to move folder_X to folder_Z.
# create empty folder Z inside folder X
dir.create('(...)/folder_X/folder_Z')
# copy the folder
file.copy('(...)/path_to_folder_Z', '(...)/folder_X')
so the second argument to file.copy shold be just folder_X, and not the newly created folder_Z inside folder_X.
Because if you do that, the folder structure will be like this, which is probably not what you want:
(...)/folder_X/folder_Z/folder_Z
(Maybe this will save somebody the 10 minutes or so it took me to figure out)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With