ADVERTISEMENT
ADVERTISEMENT

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

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?

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 »



ADVERTISEMENT
ADVERTISEMENT


Comments and Discussions!



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.