90

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
  • 1,296
  • 1
  • 8
  • 12

4 Answers4

85

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

48

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

hcchang84
  • 3
  • 5
Evan Shaw
  • 23,839
  • 7
  • 70
  • 61
23

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.

030
  • 10,842
  • 12
  • 78
  • 123
-5

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.

Michael Dorner
  • 17,587
  • 13
  • 87
  • 117
Jjed
  • 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
  • 2
    Russ 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
  • 5
    To 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