I would like to ask how can I check a file's status (whether it is opened or closed) before reading in R programming?
I have tried myfile = open(filenames)
; it doesn't work.
I would like to ask how can I check a file's status (whether it is opened or closed) before reading in R programming?
I have tried myfile = open(filenames)
; it doesn't work.
I think the trick is to use open = "w"
to open for writing. This seems to work perfectly for me:
file.opened <- function(path) {
suppressWarnings(
"try-error" %in% class(
try(file(path,
open = "w"),
silent = TRUE
)
)
)
}
After I open an Excel file:
file.opened("C:\\Folder\\tbl1.xlsx")
# TRUE
And when I close it:
file.opened("C:\\Folder\\tbl1.xlsx")
# FALSE
When you use the function file
a connection to the file is returned:
con <- file(description="path/to/file", ...)
You can check to see if this is open using the isOpen
function, which will return a logical
(TRUE
, FALSE
, or NA
).
If you don't have a connection
in your R session, or the connection has been deleted, then the connection is closed:
An excerpt of ?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.
File connections can be opened and closed using open
and close
respectively.
For Excel files, I used the following approach and it works in my computer : rename the Excel file with it's name. If the Excel file is opened, it returns FALSE. If the Excel file is closed, it returns TRUE.
file.rename(from = "C:/Users/xxx/Desktop/Test file access/file1.xlsx",
to = "C:/Users/xxx/Desktop/Test file access/file1.xlsx")