×

Golang Tutorial

Golang Reference

Golang Programs

Golang Practice

Golang Miscellaneous

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 [Last updated : March 05, 2023]

Getting the directory name from a path in Golang

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?

Golang code to get the directory name from a 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 »





Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.