2016-04-19 222 views
0

我在R中使用了命令file.copy,它引發了一個錯誤,但是我找不到原因。file.copy in R not working

file.copy(from="Z:/Ongoing/Test", to = "C:/Users/Darius/Desktop", overwrite = TRUE, recursive = TRUE) 

Warning message: 
In file.copy(from = "Z:/Ongoing/Test",: 
problem copying Z:/Ongoing/Test to C:/Users/Darius/Desktop/Test: No such file or directory 

任何人都可以看到問題嗎?命令行不起作用,即使它只給你一個警告信息。

+0

那麼,你確定源路徑是有效的嗎?文件是否存在? – michel404

+0

'Z:/正在進行/測試'是一個文件或目錄?有沒有一個名爲「測試」的文件和目錄? –

+0

什麼是list.files(「Z:/ Ongoing /」返回?是否有一個名爲(exacly)「Test」的文件?我懷疑可能有一個名爲「test.doc」或「Test.xlsx」的文件,而你認爲它是因爲你的文件瀏覽器隱藏數據而被命名爲「測試」 –

回答

4

其實,我不認爲有任何直接的方法來複制目錄。我寫了一個可以幫助你的功能。

這個函數有輸入兩個參數:

從:目錄的完整路徑要複製

:從和:到該目錄將被複制

假設位置只是一個目錄的路徑。

dir.copy <- function(from, to){ 

    ## check if from and to directories are valid 
    if (!dir.exists(from)){ 
    cat('from: No such Directory\n') 
    return (FALSE) 
    } 
    else if (!dir.exists(to)){ 
    cat('to: No such Directory\n') 
    return (FALSE) 
    } 

    ## extract the directory name from 'from' 
    split_ans <- unlist(strsplit(from,'/')) 

    dir_name <- split_ans[length(split_ans)] 

    new_to <- paste(to,dir_name,sep='/') 

    ## create the directory in 'to' 
    dir.create(new_to) 

    ## copy all files in 'to' 
    file_inside <- list.files(from,full.names = T) 

    file.copy(from = file_inside,to=new_to) 

    ## copy all subdirectories 
    dir_inside <- list.dirs(path=from,recursive = F) 

    if (length(dir_inside) > 0){ 
    for (dir_name in dir_inside) 
     dir.copy(dir_name,new_to) 
    } 

    return (TRUE) 
} 
+0

它不是一個文件,而是一個名爲「test」的整個文件夾,所以我在尋找的是將整個文件夾及其中的文件複製到新位置。 – Darius

+0

@Stibu在發佈問題的那一刻,問題不清楚現在,我已經編輯瞭解決方案以符合要求 –

+1

謝謝@KunalPuri。這是一個很好的答案,它的效果非常好。 – Darius