How do I create crossplatform file paths in Go?
36,942
Solution 1
Use path/filepath
instead of path
. path
is intended for forward slash-separated paths only (such as those used in URLs), while path/filepath
manipulates paths across different operating systems.
Solution 2
Based on the answer of @EvanShaw and this blog the following code was created:
package main
import (
"fmt"
"os"
"path/filepath"
)
func main() {
p := filepath.FromSlash("path/to/file")
fmt.Println("Path: " + p)
}
returns:
Path: path\to\file
on Windows.
Author by
Jjed
Updated on July 05, 2022Comments
-
Jjed almost 2 years
I want to open a given file
"directory/subdirectory/file.txt"
in golang. What is the recommended way to express such a path in an OS agnostic way (ie backslashes in Windows, forward slashes in Mac and Linux)? Something like Python'sos.path
module? -
Jjed about 12 years@Atom I don't own a Windows machine. Russ Cox says Go treats '/' as the path separator on all platforms, which seems good enough to me.
-
Admin about 12 yearsRuss made that comment on 2010-01-09. There have been some changes to path handling since then: see golang.org/doc/devel/weekly.html#2011-03-07
-
Flowchartsman about 9 yearsTo be perfectly clear, this answer is no longer correct. path/filepath is now always the correct answer to this question.
-
QtRoS over 6 yearsMust be marked as right answer, quite easier to understand - just use filepath everywhere and... profit!
-
030 almost 6 yearsCould you add an example?