Iain S
Iain S

Reputation: 2713

How to check if a filename is writeable in R?

How can I check if a specific filename can be written to? Ideally I would like a function that works in the same way as file.exists() - it returns TRUE or FALSE, and doesn't spit out any errors whilst testing.

The ideal example:

filename = "X:/an/invalid/path"
file.writable(filename) # returns FALSE

I have not found a function that already does this, and can't really think about how to go about it.

One idea would be to try writing some junk data to filename, but I can't figure out the intricacies of using try() or tryCatch() to avoid lots of error messages coming out. That also has the downside of overwriting the filename, which you might not want to happen.

Upvotes: 14

Views: 2899

Answers (2)

Rorschach
Rorschach

Reputation: 32446

Edit

After looking at the function suggested by @Marek, it turns out there is already a function that does this in base called file.access. If you read the warnings, they discuss the problems mentioned by @KonradRudolph in the comments (ie. file access can change).

So, all you need to do is

## Mode 2 for write permission
file.access(filename, mode=2)  # 0 success / -1 failure

Doing what you suggest (as @NickK pointed out this will overwrite the file!)

file.writable <- function(fname)
    tryCatch({
        suppressWarnings(write.table(1, fname))
    }, error=function(e) FALSE)

filename = "X:/an/invalid/path"
file.writable(filename)
# [1] FALSE

Upvotes: 15

Marek
Marek

Reputation: 50744

There is is.writable function in Hadley's assertthat package.

You could use it to write your function as:

file.writable <- function(path) {
    assertthat::is.string(path) &&
    file.exists(path) &&
    assertthat::is.writeable(path)
}

Upvotes: 7

Related Questions