Reputation: 36597
What's the best way to determine if a character is a valid file path? So CheckFilePath( "my*file.csv")
would return FALSE
(on windows * is invalid character), whereas CheckFilePath( "c:\\users\\blabla\\desktop\\myfile.csv" )
would return TRUE
.
Note that a file path can be valid but not exist on disk.
Upvotes: 3
Views: 4074
Reputation: 18625
I would suggest trying checkPathForOutput
function offered by the checkmate
package. As stated in the linked documentation, the function:
Check[s] if a file path can be safely be used to create a file and write to it.
checkmate::checkPathForOutput(x = tempfile(pattern = "sample_test_file", fileext = ".tmp"))
# [1] TRUE
checkmate::checkPathForOutput(x = "c:\\users\\blabla\\desktop\\myfile.csv")
# [1] TRUE
\0
character should not be used in Linux1 file names:
checkmate::check_path_for_output("my\0file.csv")
# Error: nul character not allowed (line 1)
1 Not tested on Windows, but looking at the code of checkmate::check_path_for_output
indicates that function should work correctly on MS Windows system as well.
Upvotes: 2
Reputation: 263451
This is the code that save
is using to perform that function:
....
else file(file, "wb")
on.exit(close(con))
}
else if (inherits(file, "connection"))
con <- file
else stop("bad file argument")
......
Upvotes: 3
Reputation: 94267
No, there's no way to do this (reliably). I don't see an operating system interface in neither Windows nor Linux to test this. You would normally try and create the file and get a fail message, or try and read the file and get a 'does not exist' kind of message.
So you should rely on the operating system to let you know if you can do what you want to do to the file (which will usually be read and/or write).
I can't think of a reason other than a quiz ("Enter a valid fully-qualified Windows file path:") to want to know this.
Upvotes: 1
Reputation: 69221
Perhaps file.exists()
is what you're after? From the help page:
file.exists returns a logical vector indicating whether the files named by its argument exist.
(Here ‘exists’ is in the sense of the system's stat call: a file will be reported as existing only
if you have the permissions needed by stat. Existence can also be checked by file.access, which
might use different permissions and so obtain a different result.
Several other functions to tap into the computers file system are available as well, also referenced on the help page.
Upvotes: 4