如何在Go中使用相对路径打开文件? [英] How can I open files using relative paths in Go?

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

问题描述

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

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

而且这种方法很好,但这不是完全可移植的。在我的情况下,我想要打开的文件在我的GOPATH中,例如:

  / Users / matt / Dev / go由于<$ c  $ c> data 文件夹放在源代码旁边,我很想指定相对路径:

  data / file.txt 

但是我得到这个错误:


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

如何使用它们的相对路径打开文件,特别是如果它们与我的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:

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

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

解决方案

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

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中使用相对路径打开文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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