如何打开与我的 GOPATH 相关的文件? [英] How can I open files relative to my 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屋!