Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the first directory of a path in GO

In Go, is it possible to get the root directory of a path so that

foo/bar/file.txt

returns foo? I know about path/filepath, but

package main

import (
        "fmt"
        "path/filepath"
)

func main() {
        parts := filepath.SplitList("foo/bar/file.txt")
        fmt.Println(parts[0])
        fmt.Println(len(parts))
}

prints foo/bar/file.txt and 1 whereas I would have expected foo and 3.

like image 655
Stefan Avatar asked Nov 09 '15 21:11

Stefan


People also ask

How to extract directory name from path?

Use os. path. dirname() to get the directory folder (name) from a path string.

How do you get a path in Golang?

Getwd functionis used to get the current working directory in Golang, the function returns the rooted path name and if the current directory can be reached via multiple paths, the function can return any one of them. The func returns two things the directory and also error, if there is no error it returns nil.

How to get directory from file path in Python?

dirname() method in Python is used to get the directory name from the specified path. Parameter: path: A path-like object representing a file system path. Return Type: This method returns a string value which represents the directory name from the specified path.

What is path in Filepath?

A path is a string of characters used to uniquely identify a location in a directory structure. It is composed by following the directory tree hierarchy in which components, separated by a delimiting character, represent each directory.


Video Answer


2 Answers

Simply use strings.Split():

s := "foo/bar/file.txt"
parts := strings.Split(s, "/")
fmt.Println(parts[0], len(parts))
fmt.Println(parts)

Output (try it on the Go Playground):

foo 3
[foo bar file.txt]

Note:

If you want to split by the path separator of the current OS, use os.PathSeparator as the separator:

parts := strings.Split(s, string(os.PathSeparator))

filepath.SplitList() splits multiple joined paths into separate paths. It does not split one path into folders and file. For example:

fmt.Println("On Unix:", filepath.SplitList("/a/b/c:/usr/bin"))

Outputs:

On Unix: [/a/b/c /usr/bin]
like image 132
icza Avatar answered Sep 16 '22 20:09

icza


Note that if you just need the first part, strings.SplitN is at least 10 times faster from my testing:

package main
import "strings"

func main() {
   parts := strings.SplitN("foo/bar/file.txt", "/", 2)
   println(parts[0] == "foo")
}

https://golang.org/pkg/strings#SplitN

like image 34
Zombo Avatar answered Sep 16 '22 20:09

Zombo