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's os.path
module?
4 Answers
For creating and manipulating OS-specific paths directly use os.PathSeparator
and the path/filepath
package.
An alternative method is to always use '/'
and the path
package throughout your program. The path
package uses '/'
as path separator irrespective of the OS. Before opening or creating a file, convert the /-separated path into an OS-specific path string by calling filepath.FromSlash(path string)
. Paths returned by the OS can be converted to /-separated paths by calling filepath.ToSlash(path string)
.
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.
Example:
package main
import (
"fmt"
"path/filepath"
)
func main() {
path := filepath.Join("home", "hello", "world.txt")
fmt.Println(path)
}
Go Playground: https://go.dev/play/p/2Fpb_vJzvSb
-
3Must be marked as right answer, quite easier to understand - just use filepath everywhere and... profit! – QtRoS Oct 23 '17 at 14:54
-
Could you add an example? – 030 May 27 '18 at 12:58
Go treats forward slashes (/
) as the universal separator across all platforms [1]. "directory/subdirectory/file.txt"
will be opened correctly regardless of the runtime operating system.

- 17,587
- 13
- 87
- 117

- 1,296
- 1
- 8
- 12
-
1@Atom I don't own a Windows machine. [Russ Cox says Go treats '/' as the path separator on all platforms](http://groups.google.com/group/golang-nuts/browse_thread/thread/5527660c2d860ca3), which seems good enough to me. – Jjed Feb 21 '12 at 06:33
-
2Russ made that comment on 2010-01-09. There have been some changes to path handling since then: see http://golang.org/doc/devel/weekly.html#2011-03-07 – Feb 21 '12 at 06:57
-
5To be perfectly clear, this answer is no longer correct. path/filepath is now always the correct answer to this question. – Flowchartsman Apr 03 '15 at 21:09