Use R to Check and See if a File is Open and Force-Close it

Good afternoon, fellow R users. I have another question for you all.

I'm currently finalizing my R text mining code and I want to be able to force-close the final data file, if it should be open on the user's computer. The general idea is that, since this code overwrites the file each time it is run, forcing it to be closed would be a nice way to guarantee that I don't get permission / lock errors.

The idea is as follows: if file = open, close the file, else nothing

Does anyone out there know of a certain package or certain line of code that I might use for this sort of thing?

Thanks!

Upvotes: 1

Views: 1598

Answers (2)

MS Berends
MS Berends

Reputation: 5269

isOpen only checks if the connection is open, not the file.

This does the job:

file.opened <- function(path) {
  suppressWarnings(
    "try-error" %in% class(
      try(file(path, 
               open = "w"), 
          silent = TRUE
      )
    )
  )
}

It checks whether a file can be opened to write (open = "w"), which is not possible when the file is opened by a user. I use it to check whether an Excel file has been opened or not.

Upvotes: 2

Ivan Chernyshov
Ivan Chernyshov

Reputation: 263

isOpen function is exactly what you want. See more here.

Upvotes: 0

Related Questions