Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Preventing duplicate slashes in file paths

Tags:

r

filepath

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.

like image 457
nsheff Avatar asked Oct 18 '22 07:10

nsheff


1 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)
}
like image 112
Jerry T Avatar answered Oct 21 '22 06:10

Jerry T