Moving files between folders

RFile IoFile Copying

R Problem Overview


I want to copy/paste a file from one folder to another folder in windows using R, but it's not working. My code:

> file.rename(from="C:/Users/msc2/Desktop/rabata.txt",to="C:/Users/msc2/Desktop/Halwa/BADMASHI/SCOP/rabata.tx")

[1] FALSE

R Solutions


Solution 1 - R

If you wanted a file.rename()-like function that would also create any directories needed to carry out the rename, you could try something like this:

my.file.rename <- function(from, to) {
    todir <- dirname(to)
    if (!isTRUE(file.info(todir)$isdir)) dir.create(todir, recursive=TRUE)
    file.rename(from = from,  to = to)
}

my.file.rename(from = "C:/Users/msc2/Desktop/rabata.txt",
               to = "C:/Users/msc2/Desktop/Halwa/BADMASHI/SCOP/rabata.txt")

Solution 2 - R

Please just be aware that file.rename will actually delete the file from the "from" folder. If you want to just make a duplicate copy and leave the original in its place, use file.copy instead.

Solution 3 - R

Use file.copy() or fs::file_copy()

file.copy(from = "path_to_original_file",
          to   = "path_to_move_to")

Then you can remove the original file with file.remove():

file.remove("path_to_original_file")

Update 2021-10-08: you can also use fs::file_copy(). I like {fs} for consistent file and directory management from within R.

Solution 4 - R

You can try the filesstrings library. This option will move the file into a directory. Example code:

First, we create a sample directory and file:

dir.create("My_directory")
file.create("My_file.txt")

Second, we can move My_file.txt into the created directory My_directory:

file.move("My_file.txt", "My_directory")

Solution 5 - R

You are missing a "t" letter in the second extension. Try this:

file.rename(from="C:/Users/msc2/Desktop/rabata.txt",to="C:/Users/msc2/Desktop/Halwa/BADMASHI/SCOP/rabata.txt").

Additionally, it could be worth it to try the file.copy() function. It is specifically designed to copy files instead of renaming.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionSagar NikamView Question on Stackoverflow
Solution 1 - RJosh O'BrienView Answer on Stackoverflow
Solution 2 - RdxjView Answer on Stackoverflow
Solution 3 - RRich PaulooView Answer on Stackoverflow
Solution 4 - RRRuizView Answer on Stackoverflow
Solution 5 - RJara SalueñaView Answer on Stackoverflow