Moving files between folders

2019-01-13 20:24发布

问题:

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

回答1:

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")


回答2:

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.



回答3:

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")