The filepath package in Go allows us to analyze and construct absolute file paths that can apply to multiple operating systems. For example, file paths in Linux use a forward slash as /dir/dir/dir/file while file-paths in Windows uses backward slashes as: C:users

Usernamedirdirfile.

This article will learn how to construct file paths using the join() method from the path package.

Golang Filepath.Join()

The syntax for the function is as shown:

func Join(elem …string) string

The function takes any number of string arguments. It then takes each argument and creates a hierarchical path as a string.

Using the Join method is very efficient as it will depend on the operating system to determine the filepath format.

Suppose we have a file in dir1, dir2, dir3. To create a path to the file using the Join method, we can do:

package main


import (


    “fmt”


    “path/filepath”

)


func main() {


    path := filepath.Join(“dir1”, “dir2”, “dir3”, “file.txt”)


    fmt.Println(“Path => “, path)

}

If we execute the code above on a Windows machine, you get an output as:

Path =>  dir1dir2dir3file.txt

On Linux, however, we can get an output as:

As you can see, using the Join method provides a very dynamic and efficient method of creating filepaths instead of concatenating various elements.

Example 2

If you pass an empty string as the argument to the Join string, the function will ignore it as shown:

path := filepath.Join(“”)


fmt.Println(“Path => “, path)

The above example should return an empty path as:

Example 3

Consider the example shown below:

fmt.Println(filepath.Join(“dir1//dir2//dir3”, “file.txt”))

The code above should return the result as:

Example 4

To get the file extension of a file in the provided path, you can use the Ext method. For example:

file := “info.config”


extension := filepath.Ext(file)


fmt.Println(extension)

The resulting output is as shown:

Conclusion

This article covered how to create absolute paths using the Join method from the filepath package. This is a very useful package when you need to create paths that can be exported across multiple operating systems.

Goodbye, Fellow Gophers!!

About the author

<img data-del="avatar" data-lazy-src="https://kirelos.com/wp-content/uploads/2022/02/echo/john-150×150.png621352afddca1.jpg" height="112" src="data:image/svg xml,” width=”112″>

John Otieno

My name is John and am a fellow geek like you. I am passionate about all things computers from Hardware, Operating systems to Programming. My dream is to share my knowledge with the world and help out fellow geeks. Follow my content by subscribing to LinuxHint mailing list