我想问一下,在R编程中,如何在读取文件之前检查文件的状态(是否已打开或关闭)?
我尝试了
我尝试了
myfile = open(filenames)
,但它没有起作用。我认为关键是使用open = "w"
进行写入打开。这对我来说似乎完美地起作用:
file.opened <- function(path) {
suppressWarnings(
"try-error" %in% class(
try(file(path,
open = "w"),
silent = TRUE
)
)
)
}
file.opened("C:\\Folder\\tbl1.xlsx")
# TRUE
当我关闭它时:
file.opened("C:\\Folder\\tbl1.xlsx")
# FALSE
当您使用函数file
时,将返回到文件的连接:
con <- file(description="path/to/file", ...)
isOpen
函数来检查它是否打开,该函数将返回一个逻辑值(TRUE
、FALSE
或NA
)。connection
,或者连接已被删除,则连接将关闭:
?file
的摘录: ‘close’ closes and destroys a connection. This will happen
automatically in due course (with a warning) if there is no longer
an R object referring to the connection.
文件连接可以使用open
和close
分别打开和关闭。
file
而不是 open
:) - Scott RitchieisOpen
不会检查文件是否在任何应用程序中打开,它检查特定连接是否在 R 中打开,例如在上面的情况下,是 con
变量。 - Scott Ritchiefile.rename(from = "C:/Users/xxx/Desktop/Test file access/file1.xlsx",
to = "C:/Users/xxx/Desktop/Test file access/file1.xlsx")
file(path, open = "w")
似乎会用一个空文件来覆盖已存在的文件。而file(path, open = "r+")
会尝试写入文件,但事实上并不写入任何内容(即保留已有数据)。请参阅?file
中的模式部分。 - vorpal