generativist / til

Go Has No File Part Splitter

Or, HOWTO Split a File Path into a Slice of It's Parts

The Go standard library is impressively completeespecially if you are writing network services. Consequently, I was a little surprised that I couldn’t split a file path into all of it’s path elements in an operating system independent way.

There is a Split method that gives you (dir, file),

import (
	"fmt"
	"path/filepath"
)

dir, file := filepath.Split("your/file/path")
_, _ = fmt.Printf(`("%s", "%s")`, dir, file)
("your/file/", "path")

but that demands a recursive solution that seems like overkill.Technically, it proceeds right-to-left, so it doesn’t rescan sequences already scanned. But, this would then require reversing the slice after scanning.

However, the os package does define a file path separator rune,

import "os"

_, _ = fmt.Printf("%q", rune(os.PathSeparator))
'/'

Combined with the FieldsFunc from the strings package, this gives the near-one-liner that I expected already,

import "strings"

func pathToParts(path string) (parts []string) {
	return strings.FieldsFunc(path, func(c rune) bool {
		return os.PathSeparator == c
	})
}

pathToParts("/a/b/c/d/")
[a b c d]