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.
How to check for a file and whether it is readable and writable. The bash shell test command has many more options as follows: -w FILE : FILE exists and write permission is granted. -x FILE : FILE exists and execute (or search) permission is granted.
Method 1: Using File.exists() The function file. exists() returns a logical vector indicating whether the file mentioned in the function existing or not. Note: Make sure that to provide a file path for those, not in the current working directory. Return value: The function file.
To get the extension of a file in R, use the file_ext() method. The file_ext() is not a built-in R method. To use the file_ext() method, you need to import the tools library. Now, you can use the file_ext() method.
The current working directory is displayed by the RStudio IDE within the title region of the Console pane. You can also check your current working directory by running the command getwd() in the console.
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)
}
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
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