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
+28.3k Golang : missing Git command
+10.2k Golang : Calculate Relative Strength Index(RSI) example
+16.1k Golang : How to tell if a file is compressed either gzip or zip ?
+5k nginx : force all pages to be SSL
+21.5k Golang : Round float to precision example
+9.1k Golang : Check a web page existence with HEAD request example
+11.6k Golang : Arithmetic operation with numerical slices or arrays example
+11k Golang : Determine if time variables have same calendar day
+31k Golang : Copy directory - including sub-directories and files
+15k Golang : Read a file line by line
+20.9k Golang : Join arrays or slices example
+12.3k Swift : Convert (cast) Int to String ?