[英]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.