移动目录的强大跨平台方法

Jer*_*oen 6 r cran

什么是自说移动整个目录最可靠的方法/tmp/RtmpK4k1Ju/oldname/home/jeroen/newname?最简单的方法是,file.rename这并不总是有效,例如当fromto不同的磁盘上.在这种情况下,需要以递归方式复制整个目录.

这是我想出来的东西,但它有点涉及,我不确定它是否可以跨平台工作.有没有更好的办法?

dir.move <- function(from, to){
  stopifnot(!file.exists(to));
  if(file.rename(from, to)){
    return(TRUE)
  }
  stopifnot(dir.create(to, recursive=TRUE));
  setwd(from)
  if(all(file.copy(list.files(all.files=TRUE, include.dirs=TRUE), to, recursive=TRUE))){
    #success!
    unlink(from, recursive=TRUE);
    return(TRUE)
  }
  #fail!
  unlink(to, recursive=TRUE);
  stop("Failed to move ", from, " to ", to);
}
Run Code Online (Sandbox Code Playgroud)

lcn*_*lcn 3

我认为file.copy应该足够了。

\n\n
file.copy(from, to, overwrite = recursive, recursive = FALSE,\n          copy.mode = TRUE)\n
Run Code Online (Sandbox Code Playgroud)\n\n

?file.copy

\n\n
from, to: character vectors, containing file names or paths.  For\n         \xe2\x80\x98file.copy\xe2\x80\x99 and \xe2\x80\x98file.symlink\xe2\x80\x99 \xe2\x80\x98to\xe2\x80\x99 can alternatively\n         be the path to a single existing directory.\n
Run Code Online (Sandbox Code Playgroud)\n\n

和:

\n\n
recursive: logical.  If \xe2\x80\x98to\xe2\x80\x99 is a directory, should directories in\n          \xe2\x80\x98from\xe2\x80\x99 be copied (and their contents)?  (Like \xe2\x80\x98cp -R\xe2\x80\x99 on\n          POSIX OSes.)\n
Run Code Online (Sandbox Code Playgroud)\n\n

从描述中recursive我们知道from可以有目录。因此,在上面的代码中,没有必要在复制之前列出所有文件。只需记住该to目录将是复制的from. 例如,在 后面file.copy("dir_a/", "new_dir/", recursive = T),会有一个dir_aunder new_dir

\n\n

您的代码已经很好地完成了删除部分。unlink有一个不错的recursive选择,但file.remove没有。

\n\n
unlink(x, recursive = FALSE, force = FALSE)\n
Run Code Online (Sandbox Code Playgroud)\n

  • ...然后删除原来的。 (2认同)