Golang : Get current file path of a file or executable
Getting a file path in Golang is not that straight forward with just a single function call. In this tutorial, we will learn how to get the current file path of a file with filepath.Abs.
getfilepath.go
package main
import (
"fmt"
"log"
"os"
"path/filepath"
)
func main () {
filename := os.Args[1] // get command line first parameter
filedirectory := filepath.Dir(filename)
thepath, err := filepath.Abs(filedirectory)
if err != nil {
log.Fatal(err)
}
fmt.Println(thepath)
}
Executing > go run getfilepath.go somefile
will return the current path of the somefile
For finding out the executable file path. In most cases, os.Getwd should do the job.
You can use the above code as well to find the current path of the executing program. Just change the line
filename := os.Args[1] // get command line first parameter
to
filename := os.Args[0] // use own filename
Hope this tutorial can be useful to you.
References :
http://golang.org/pkg/path/filepath/
http://andrewbrookins.com/tech/golang-get-directory-of-the-current-file/
See also : Golang : File path independent of Operating System
By Adam Ng
IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.
Advertisement
Tutorials
+31.2k Golang : How to check if a date is within certain range?
+10.7k Golang : Gorilla web tool kit secure cookie example
+4.9k Golang : List all packages and search for certain package
+5.2k Golang : Join lines with certain suffix symbol example
+4.6k Golang : Get S3 or CloudFront object or file information
+11.6k Golang : Convert int(year) to time.Time type
+13.3k Golang : How to shuffle elements in array or slice?
+9.6k Golang : Fix go.exe is not compatible with the version of Windows you're running
+25.5k Golang : dial tcp: too many colons in address
+4.4k Golang : Generate Interleaved 2 inch by 5 inch barcode
+30.6k Golang : Validate email address with regular expression
+22.2k Golang : Print out struct values in string format