[英]Robust cross-platform method of moving a directory
将整个目录从/tmp/RtmpK4k1Ju/oldname
到/home/jeroen/newname
的最强大的方法是什么? 最简单的方法是file.rename
但这并不总是有效,例如当from
和to
在不同的磁盘上时。 在这种情况下,需要以递归方式复制整个目录。
这是我想出来的东西,但它有点涉及,我不确定它是否可以跨平台工作。 有没有更好的办法?
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);
}
我认为file.copy
就足够了。
file.copy(from, to, overwrite = recursive, recursive = FALSE,
copy.mode = TRUE)
来自?file.copy
:
from, to: character vectors, containing file names or paths. For
‘file.copy’ and ‘file.symlink’ ‘to’ can alternatively
be the path to a single existing directory.
和:
recursive: logical. If ‘to’ is a directory, should directories in
‘from’ be copied (and their contents)? (Like ‘cp -R’ on
POSIX OSes.)
大约从描述recursive
我们知道from
能有目录。 因此,在上面的代码中列出复制前的所有文件是不必要的。 而只记得to
目录将是复制的父母from
。 例如,在file.copy("dir_a/", "new_dir/", recursive = T)
, dir_a
下会有一个new_dir
。
你的代码很好地完成了删除部分。 unlink
有一个很好的recursive
选项, file.remove
没有。
unlink(x, recursive = FALSE, force = FALSE)
为什么不直接调用系统:
> system('mv /tmp/RtmpK4k1Ju/oldname /home/jeroen/newname')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.