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
.
Use os. path. dirname() to get the directory folder (name) from a path string.
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.
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.
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.
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]
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With