To get the absolute path of a file or directory in Golang, you can use the “filepath.Abs()” function. The filepath.Abs() is a built-in function that accepts a path and returns “an absolute representation of the specified path”.
An absolute path is a complete path to a file or directory that confines the exact location of the file or directory on a computer. It starts from the file system’s root directory and includes all the intermediate directories, subdirectories, and the file’s name or directory.
Process flow diagram of Abs() function
Syntax
func Abs(path string) (string, error)
Parameters
The “path” is the specified path.
Return value
It returns an absolute representation of the specified path.
Example 1
package main
import (
"fmt"
"path/filepath"
)
func main() {
absPath, err := filepath.Abs("../file.txt")
if err != nil {
panic(err)
}
// Print the absolute path of the file
fmt.Println(absPath)
}
Output
/Users/krunallathiya/Desktop/Code/R/file.txt
Example 2
package main
import (
"fmt"
"path/filepath"
)
func main() {
fmt.Println(filepath.Abs("/"))
fmt.Println(filepath.Abs("."))
fmt.Println(filepath.Abs(":"))
fmt.Println(filepath.Abs("/."))
fmt.Println(filepath.Abs("//"))
fmt.Println(filepath.Abs(":/"))
}
Output
/ <nil>
/Users/krunallathiya/Desktop/Code/pythonenv/env <nil>
/Users/krunallathiya/Desktop/Code/pythonenv/env/: <nil>
/ <nil>
/ <nil>
/Users/krunallathiya/Desktop/Code/pythonenv/env/: <nil>
That’s it.

Krunal Lathiya is a seasoned Computer Science expert with over eight years in the tech industry. He boasts deep knowledge in Data Science and Machine Learning. Versed in Python, JavaScript, PHP, R, and Golang. Skilled in frameworks like Angular and React and platforms such as Node.js. His expertise spans both front-end and back-end development. His proficiency in the Python language stands as a testament to his versatility and commitment to the craft.