Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check a file is opened or closed in R

Tags:

file

r

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.

like image 619
user3003009 Avatar asked Oct 17 '25 00:10

user3003009


2 Answers

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
like image 168
MS Berends Avatar answered Oct 19 '25 15:10

MS Berends


Based on the answer by MS Berends, with modifications:

  • Check the file actually exists, otherwise it look like non-existent files are open
  • Access the file in r+ mode instead of w, because the latter sometimes does weird overwriting
  • Close the file connection, so it doesn't give you a warning message when it automatically closes it for you later
is_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)
}
like image 37
Oliver Avatar answered Oct 19 '25 14:10

Oliver



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!