Preventing duplicate slashes in file paths

我只是一个虾纸丫 提交于 2019-12-08 01:18:28

问题


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"

[EDIT] In addition, how to join tempdir() and file name on windows:

> dir <- tempdir()
[1] "C:\\Users\\username\\AppData\\Local\\Temp\\Rtmp2F1zSJ"
> file.path(dir, "file.txt")
[1] "C:\\Users\\username\\AppData\\Local\\Temp\\Rtmp2F1zSJ/file.txt"

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


回答1:


You could replace the // with / using gsub if it is too annoying. You could put it in a custom function for ease

file.path2 = function(..., fsep = .Platform$file.sep){
    gsub("//", "/", file.path(..., fsep = fsep))
}

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

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



回答2:


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)
}


来源:https://stackoverflow.com/questions/45619522/preventing-duplicate-slashes-in-file-paths

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!