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
Based on the answer by MS Berends, with modifications:
r+
mode instead of w
, because the latter sometimes does weird overwritingis_file_open <- function(path) {
# Make sure the file actually exists
assertthat::assert_that(file.exists(path))
# Try to open a connection to the file. Will fail if it's open
attempted_connection <- suppressWarnings(
try(file(path, open = "r+"), silent = TRUE)
)
# If the attempted connection gave an error, the file is probably open
is_open <- inherits(attempted_connection, "try-error")
# Good practice: close the connection if we did manage to open it
if (!is_open) {
close(attempted_connection)
}
return(is_open)
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With