在 R 中写入文件后关闭文件

Pen*_*eng 5 r file

在其他语言中,当您将数据写入文件时,必须关闭该文件。我发现在 R 中,将数据写入文件后不需要关闭文件,我是对的吗?如果我写:

require(quantmod)  
getSymbols("GS")  
write(GS,'test')
Run Code Online (Sandbox Code Playgroud)

Jul*_*ora 6

您不需要关闭该文件,因为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>
Run Code Online (Sandbox Code Playgroud)

  • 让我们澄清一下,这是当“write”或“cat”的“file”参数是一个字符时的行为,它被解释为文件名(此处为“test”)。如果文件是通过文件连接打开的:“filehandle &lt;- file('test')”并传递给“write(GS, filehandle)”,则建议稍后使用“close(filehandle)”关闭文件句柄`。 (9认同)
  • @flodel我认为你的评论值得回答,因为正如你所指出的,情况要复杂得多。 (2认同)