snippetgoMajor
How do I create crossplatform file paths in Go?
Viewed 0 times
pathshowfilecrossplatformcreate
Problem
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?Solution
For creating and manipulating OS-specific paths directly use
An alternative method is to always 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).Context
Stack Overflow Q#9371031, score: 98
Revisions (0)
No revisions yet.