Q:

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

belongs to collection: Golang path/filepath Package Programs

0

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.

All Answers

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

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?

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

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

total answers (1)

<< How to join multiple paths into a single path in G...