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.

Share:
36,942
Jjed
Author by

Jjed

Updated on July 05, 2022

Comments

  • Jjed
    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's os.path module?

  • Jjed
    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
    Admin about 12 years
    Russ 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
    Flowchartsman about 9 years
    To be perfectly clear, this answer is no longer correct. path/filepath is now always the correct answer to this question.
  • QtRoS
    QtRoS over 6 years
    Must be marked as right answer, quite easier to understand - just use filepath everywhere and... profit!
  • 030
    030 almost 6 years
    Could you add an example?