One such application is navigating directories in Windows and Unix-Like systems. For example, Windows implements its filepaths using backward slashes as: dir\dir\file.extension. Linux using a forward slash (/). Hence, having a way to create a path that is compatible with both systems is highly useful.
This guide will discover how to use the filepath package to manipulate various aspects of the file paths.
Filepath.Abs()
The Abs() method from the filepath package allows you to get the absolute path of a specified path. If the specified path is not absolute, the function will join it with the current working directory to create an absolute path.
The function syntax is as shown:
The function takes the path as a parameter and returns its absolute path or an error.
import (
"fmt"
"path/filepath"
)
funcmain() {
fmt.Println(filepath.Abs("/"))
fmt.Println(filepath.Abs("."))
fmt.Println(filepath.Abs("/windows")) // not absolute
}
If we run the code above on a Windows machine, we should get an output as:
C:\Users\csalem\Documents\workspace\filepath <nil>
C:\windows <nil>
On Linux, the code returns:
/home/debian11 <nil>
/windows <nil>
Filepath.Base()
This function returns the last element of the provided path. The function removes all the path separators before removing the last element. If the provided path is empty, the function returns “.”.
An example program is as shown:
The code above should return the last element of the path as:
If you provide a single entry to the function, it returns itself as:
Output:
Filepath.Dir()
The Dir() method returns all but the last part of the path. Think of it as the opposite of the Base() method.
The function syntax is as:
An example is as shown:
The resulting value is as:
Filepath.Join()
This is one of the most useful methods provided by the filepath package. It is used to construct an absolute path based on the provided parameters.
The function syntax is as:
The function takes any number of elements and returns an absolute value constructed according to the target operating system.
For example:
If we run the code above on Windows, we should take a path as:
On Linux, the output is as:
Filepath.IsAbs()
You can use this function to check if the provided path is absolute. It returns true if the path is absolute and false if otherwise.
An example is as shown:
fmt.Println(filepath.IsAbs("./"))
The function returns:
true
false
Filepath.Ext()
The Ext() method returns the file extension from the provided filename. An example is as shown:
The above example should return the file extension as:
This is a wonderful method to check the file type.
Filepath.VolumeName
The VolumeName() method allows you to get the leading name of the volume from a specified path.
Example:
The function should return the volume name as:
Conclusion
Using the tutorial, you discover the basics of working with filepaths using the filepath package. Check the documentation to explore more.
Happy coding!