背景: linux golang
在程序运行中,经常需要读取文件,如果文件路径写成绝对路劲,对于程序移植到其他机器上执行时,可能会出错,找不到文件。
所以,最好的方式是写成相对路径。
实现方式:
假设有如下文件路径:
test-
- main.go
- api
- - testApi.go
package package
import (
"path"
"runtime"
"fmt"
)
func main () {
_, filename, _, ok := runtime.Caller(1)
var cwdPath string
if ok {
cwdPath = path.Join(path.Dir(filename), "") // the the main function file directory
} else {
cwdPath = "./"
}
fmt.Println("cwd path...", cwdPath )
}
(注意修改package 名字)
以上代码放在main.go 中时,执行 go run main.go
, 输出 /usr/local/go/src/runtime
以及 上述代码放在 testApi.go 中时, 依旧执行 go run main.go
输出 /home/cogoadmin/gopath/src/test
其他
python 中,文件获取自己所在的路径
import os
cwd = os.path.dirname(os.path.abspath(__file__))