在Go中与.go源文件位于同一目录中打开文件

When in a source file $PWD/dir/src.go I use

os.Open("myfile.txt")

it looks for myfile.txt in $PWD (which looks normal).

Is there way to tell Go to look for myfile.txt in the same directory as src.go ? I need something like __FILE__ in Ruby.

Go is not an interpreted language so looking for a file in the same location as the source file doesn't make any sense. The go binary is compiled and the source file doesn't need to be present for the binary to run. Because of that Go doesn't come with an equivalent to FILE. The runtime.Caller function returns the file name at the time the binary was compiled.

I think perhaps if we understood why you actually wanted this functionality we could advise you better.

A possible substitute skeleton:

func __FILE__() (fn string) {
        _, fn, _, _ = runtime.Caller(0)
        return 
}

Details here.

Use package osext

It's providing function ExecutableFolder() that returns an absolute path to folder where the currently running program executable reside (useful for cron jobs). It's cross platform.

Online documentation

package main

import (
    "github.com/kardianos/osext"
    "fmt"
    "log"
)

func main() {
    folderPath, err := osext.ExecutableFolder()
    if err != nil {
        log.Fatal(err)
    }
    fmt.Println(folderPath)
}

You can also get full executable path (similar to __FILE__):

package main

import (
    "github.com/kardianos/osext"
    "fmt"
)

func main() {
    exeAbsolutePath, _ := osext.Executable()
    fmt.Println(exeAbsolutePath)
}