Preventing duplicate slashes in file paths

Viewed 1616

I would like to build a path to a file, given a filename and a folder where that file exists. The folder may include a trailing slash or it may not. In python, os.path.join solves this problem for you. Is there a base R solution to this problem? If not, what is the recommended way in R to build file paths that do not have duplicate slashes?

This works fine:

> file.path("/path/to/folder", "file.txt")
[1] "/path/to/folder/file.txt"

But if the user provides a folder with a trailing slash, file.path does the still-functional-but-annoying double-slash:

> file.path("/path/to/folder/", "file.txt")
[1] "/path/to/folder//file.txt"

I'm looking for a built-in, 1 function answer to this common issue.

2 Answers

might be os independent, instead of explicitly coding /

joinpath = function(...) {
    sep = .Platform$file.sep
    result = gsub(paste0(sep,"{2,}"), sep, file.path(...), fixed=FALSE, perl=TRUE)
    result = gsub(paste0(sep,"$"), '', result, fixed=FALSE, perl=TRUE)
    return(result)
}
Related