Q:

How to get the directory name from a path in Golang?

belongs to collection: Golang path/filepath Package Programs

0

In the Go programming language, to get the directory name from a given path – we use the Dir() function of path/filepath package. The Dir() function returns all but the last element of the given path, typically the path's directory. After dropping the final element, Dir() function calls the Clean() function on the path, and trailing slashes are removed. If the given path is empty, it returns ".". If the given path consists entirely of separators, it returns a single separator. The returned path does not end in a separator unless it is the root directory.

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Syntax:

func Dir(path string) string

Consider the below Golang program demonstrating how to get the directory name from the given path?

package main

import (
	"fmt"
	"path/filepath"
)

func main() {
	// Defining a path
	dir := filepath.Dir("/project1/client1/file1.go")
	fmt.Println("Directory name is :", dir)
}

Output

Directory name is : /project1/client1

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

How to get the file name extension used by path in... >>
<< How to get the absolute path from a relative path ...