Jay Taylor's notes

back to listing index

Go: How to Get the Directory of the Current File

[web search]
Original source (andrewbrookins.com)
Tags: python golang dirname runtime andrewbrookins.com
Clipped on: 2016-10-16

Andrew Brookins

software engineering, the nature of good and evil, etc.

You are here:Home Technology Go: How to Get the Directory of the Current File
May 19, 2012

Go: How to Get the Directory of the Current File

In Python I often use the __file__ constant to get the directory of the current file (e.g., os.path.dirname(os.path.realpath(__file__))). While writing a Go app recently, I found that there wasn’t an immediately obvious (or searchable, even with “golang”) equivalent.

But in the annals of the golong-nuts mailing list I eventually found out about runtime.Caller(). This returns a few details about the current goroutine’s stack, including the file path.

The context of my problem was opening a data file in a shared package. What I cooked up was:

1 _, filename, _, _ := runtime.Caller(1)
2 f, err := os.Open(path.Join(path.Dir(filename), "data.csv"))
view raw gistfile1.go hosted with Image (Asset 1/3) alt= by GitHub

Sending 1 to runtime.Caller identifies the caller of runtime.Caller as the stack frame to return details about. So you you get info about the file your method is in. Check the docs for more in-depth coverage.

It’s not quite as elegant as __file__ but it works.

Filed Under: Technology