×

Golang Tutorial

Golang Reference

Golang Programs

Golang Practice

Golang Miscellaneous

How to split a path into the directory and file names in Golang?

Given a path, we have to split it into the directory and file names in Golang.
Submitted by IncludeHelp, on October 28, 2021 [Last updated : March 05, 2023]

Splitting a path into the directory and file names in Golang

In the Go programming language, to split the given path into the directory and file names – we use the Split() function of the path/filepath package. The Split() function splits the given path immediately following the final Separator, separating it into a directory and file name component. If there is no Separator in the given path, the Split() function returns an empty directory (dir) and file set to path. The returned values have the property that path = dir+file.

Syntax

func Split(path string) (dir, file string)

Consider the below Golang program demonstrating how to split a path into the directory and file names?

Golang code to split a path into the directory and file names

package main

import (
	"fmt"
	"path/filepath"
)

func main() {
	// Defining paths
	path1 := "/programs/course1/hello1.go"
	path2 := "/programs/hello2.go"

	// Calling Split() function to get the
	// DIR and FILE names
	dir, file := filepath.Split(path1)
	fmt.Println("From the path:", path1)
	fmt.Println("dir:", dir)
	fmt.Println("file:", file)

	dir, file = filepath.Split(path2)
	fmt.Println("From the path:", path1)
	fmt.Println("dir:", dir)
	fmt.Println("file:", file)
}

Output

From the path: /programs/course1/hello1.go
dir: /programs/course1/
file: hello1.go
From the path: /programs/course1/hello1.go
dir: /programs/
file: hello2.go

Golang path/filepath Package Programs »





Comments and Discussions!

Load comments ↻





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