ADVERTISEMENT
ADVERTISEMENT

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

Given a path, we have to get the directory name in Golang.
Submitted by IncludeHelp, on October 27, 2021

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.

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

Golang path/filepath Package Programs »



ADVERTISEMENT




ADVERTISEMENT



Comments and Discussions!

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.