How do I create crossplatform file paths in Go?

FileIoDirectoryGo

File Problem Overview


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?

File Solutions


Solution 1 - File

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

Solution 2 - File

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 3 - File

Based on the answer of @EvanShaw and [this blog][1] 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. [1]: https://golangcode.com/cross-platform-file-paths/

Solution 4 - File

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJjedView Question on Stackoverflow
Solution 1 - Fileuser811773View Answer on Stackoverflow
Solution 2 - FileEvan ShawView Answer on Stackoverflow
Solution 3 - File030View Answer on Stackoverflow
Solution 4 - FileJjedView Answer on Stackoverflow