问题描述
我使用 io / ioutil
来读取一个小文本文件:
fileBytes,err:= ioutil.ReadFile(/ absolute / path / to / file.txt)
而且这种方法很好,但这不是完全可移植的。在我的情况下,我想要打开的文件在我的GOPATH中,例如:
/ Users / matt / Dev / go由于<$ c $ c> data
文件夹放在源代码旁边,我很想指定相对路径:data / file.txt
但是我得到这个错误:
如何使用它们的相对路径打开文件,特别是如果它们与我的Go代码一起生活?
嗯。 ..路径/文件路径
包有虽然这样做有点不方便,但它能够满足我的需求(到目前为止):
absPath,_:= filepath.Abs(../ mypackage / data / file.txt)
n我使用
absPath
来加载文件,它工作正常。
请注意,就我而言,数据文件位于与运行程序的
主要
软件包不同的软件包中。如果它全部在同一个包中,我会删除前面的../ mypackage /
。由于这个路径显然是相对的,所以不同的程序会有不同的结构,需要相应调整。
如果有更好的方式使用外部资源和Go程序并保留它便携式,随时提供另一个答案。
I'm using
io/ioutil
to read a small text file:fileBytes, err := ioutil.ReadFile("/absolute/path/to/file.txt")
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
Since the
data
folder rides right alongside the source code, I'd love to just specify the relative path:data/file.txt
But then I get this error:
How can I open files using their relative path, especially if they live alongside my Go code?
解决方案
Hmm... the
path/filepath
package hasAbs()
which does what I need (so far) though it's a bit inconvenient:absPath, _ := filepath.Abs("../mypackage/data/file.txt")
Then I use
absPath
to load the file and it works fine.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.If there's a better way to use external resources with a Go program and keep it portable, feel free to contribute another answer.
这篇关于如何在Go中使用相对路径打开文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!