2012-07-27 65 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