如何获取当前运行文件的目录? [英] How to get the directory of the currently running file?

查看:21
本文介绍了如何获取当前运行文件的目录?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 nodejs 中,我使用 __dirname .Golang 中的 this 是什么?

In nodejs I use __dirname . What is the equivalent of this in Golang?

我在谷歌上搜索并发现了这篇文章 http://andrewbrookins.com/tech/golang-get-directory-of-the-current-file/ .他使用以下代码的地方

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"))

但这在 Golang 中是正确的方式还是惯用的方式?

But is it the right way or idiomatic way to do in Golang?

推荐答案

应该这样做:

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆