簡體   English   中英

移動目錄的強大跨平台方法

[英]Robust cross-platform method of moving a directory

將整個目錄從/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);
}

我認為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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM