Username\dir\dir\file.
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:
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:
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:
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:
fmt.Println("Path => ", path)
The above example should return an empty path as:
Example 3
Consider the example shown below:
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:
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!!