如何获取当前正在运行的文件的目录? [英] How to get the directory of the currently running file?
本文介绍了如何获取当前正在运行的文件的目录?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在nodejs中,我使用 __dirname 。这在Golang中的作用是什么?
我已经使用Google搜索并找到了这篇文章 http://andrewbrookins.com/tech/golang-get-directory-of-the-current-file/ 。
_,filename,_,_:= runtime.Caller(1)
f,err := os.Open(path.Join(path.Dir(filename),data.csv))
导入(
fmt
log
os
路径/ filepath
)
func main(){
dir,err:= filepath.Abs(filepath.Dir(os.Args [0]))
if err!= nil {
log.Fatal(err)
}
fmt.Println(dir)
}
In nodejs I use __dirname . What is the equivalent of this in Golang?
I have googled and found out this article http://andrewbrookins.com/tech/golang-get-directory-of-the-current-file/ . Where he uses below code
_, filename, _, _ := runtime.Caller(1)
f, err := os.Open(path.Join(path.Dir(filename), "data.csv"))
But is it the right way or idiomatic way to do in Golang?
解决方案
This should do it:
import (
"fmt"
"log"
"os"
"path/filepath"
)
func main() {
dir, err := filepath.Abs(filepath.Dir(os.Args[0]))
if err != nil {
log.Fatal(err)
}
fmt.Println(dir)
}
这篇关于如何获取当前正在运行的文件的目录?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文