如何打开相对于我的GOPATH的文件? [英] How can I open files relative to my GOPATH?

查看:84
本文介绍了如何打开相对于我的GOPATH的文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用io/ioutil来读取一个小的文本文件:

I'm using io/ioutil to read a small text file:

fileBytes, err := ioutil.ReadFile("/absolute/path/to/file.txt")

这很好用,但这不是完全可移植的.就我而言,我要打开的文件位于我的GOPATH中,例如:

And that works fine, but this isn't exactly portable. In my case, the files I want to open are in my GOPATH, for example:

/Users/matt/Dev/go/src/github.com/mholt/mypackage/data/file.txt

由于data文件夹位于源代码的旁边,所以我只想指定相对路径:

Since the data folder rides right alongside the source code, I'd love to just specify the relative path:

data/file.txt

但随后出现此错误:

恐慌:打开data/file.txt:没有此类文件或目录

panic: open data/file.txt: no such file or directory

如何使用文件的相对路径打开文件,尤其是当文件与我的Go代码一起存放时?

How can I open files using their relative path, especially if they live alongside my Go code?

(请注意,我的问题特别是关于打开相对于GOPATH的文件.在Go中使用任何相对路径打开文件就像给出相对路径而不是绝对路径一样容易;相对于已编译的二进制文件的工作目录打开文件.对于我而言,我想相对于二进制文件的编译位置打开文件.事后看来,这是一个错误的设计决定.)

(Note that my question is specifically about opening files relative to the GOPATH. Opening files using any relative path in Go is as easy as giving the relative path instead of an absolute path; files are opened relative to the compiled binary's working directory. In my case, I want to open files relative to where the binary was compiled. In hindsight, this is a bad design decision.)

推荐答案

嗯... path/filepath软件包具有 Abs() 可以满足我的需求(到目前为止),尽管有点不方便:

Hmm... the path/filepath package has Abs() which does what I need (so far) though it's a bit inconvenient:

absPath, _ := filepath.Abs("../mypackage/data/file.txt")

然后我使用absPath加载文件,它可以正常工作.

Then I use absPath to load the file and it works fine.

请注意,就我而言,数据文件位于与我正在从中运行程序的main包分开的一个包中.如果它们都在同一个程序包中,我将删除前导../mypackage/.由于该路径显然是相对的,因此不同的程序将具有不同的结构,并且需要对此进行相应的调整.

Note that, in my case, the data files are in a package separate from the main package from which I'm running the program. If it was all in the same package, I'd remove the leading ../mypackage/. Since this path is obviously relative, different programs will have different structures and need this adjusted accordingly.

如果有更好的方法可以将外部资源与Go程序一起使用并保持可移植性,请随时提出另一个答案.

If there's a better way to use external resources with a Go program and keep it portable, feel free to contribute another answer.

这篇关于如何打开相对于我的GOPATH的文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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