2012-07-27 113 views
2

在其他語言中,當您將數據寫入文件時,必須關閉該文件。 我在R中發現,在將數據寫入數據後無需關閉文件,我是否正確? 會發生什麼,如果我寫的:在R中寫入文件後關閉文件

require(quantmod) 
getSymbols("GS") 
write(GS,'test') 
+0

這取決於你如何寫入文件。你可以發佈你使用的代碼嗎? – Andrie 2012-07-27 06:15:14

回答

3

你並不需要關閉文件,因爲write()關閉它:

> write 
function (x, file = "data", ncolumns = if (is.character(x)) 1 else 5, 
    append = FALSE, sep = " ") 
# Using cat() function 
cat(x, file = file, sep = c(rep.int(sep, ncolumns - 1), "\n"), 
    append = append) 
<bytecode: 0x053fdb10> 
<environment: namespace:base> 

> cat 
function (..., file = "", sep = " ", fill = FALSE, labels = NULL, 
    append = FALSE) 
{ 
    if (is.character(file)) 
     if (file == "") 
      file <- stdout() 
     else if (substring(file, 1L, 1L) == "|") { 
      file <- pipe(substring(file, 2L), "w") 
      # Closing here 
      on.exit(close(file)) 
     } 
     else { 
      file <- file(file, ifelse(append, "a", "w")) 
      # Or here 
      on.exit(close(file)) 
     } 
    .Internal(cat(list(...), file, sep, fill, labels, append)) 
} 
<bytecode: 0x053fdd68> 
<environment: namespace:base> 
+5

讓我們來澄清一下,這是'write'或'cat'的'file'參數是一個字符,它被解釋爲一個文件名(這裏是'test'')的行爲。如果文件是通過文件連接打開的:'filehandle < - file('test')'並傳遞給'write(GS,filehandle)',那麼建議稍後用close(文件句柄)關閉文件句柄'。 – flodel 2012-07-27 11:20:51

+1

@ flodel我想你的評論是值得回答的,因爲情況比較複雜,正如你指出的那樣。 – Andrie 2012-07-27 13:54:00