从os.Open中出现”没有这样的文件或目录”错误。

huangapple go评论76阅读模式
英文:

No such file or directory error from os.Open

问题

我正在努力解决os.Open的问题。当我在名为templates的文件夹上使用os.Open时,我不断收到“没有这样的文件或目录”错误。所以我有一个包含bin、pkg、src和templates文件夹的MVCApp文件夹。然后我在src文件夹中有一个main文件。所以我有以下代码:

basePath := "templates"
templateFolder, err := os.Open(basePath)
if err != nil {
    log.Fatal(err)
}
defer templateFolder.Close()

我认为问题与我在打开时使用的basePath有关,但我无法弄清楚我需要如何准备“templates”以便找到该目录。我确定这是一个简单的修复,但它让我困惑不已。任何帮助将不胜感激。

英文:

I am struggling to figure out an issue with os.Open. I keep getting a 'no such file or directory' error when using os.Open on a folder named templates. So I have my folder MVCApp with bin pkg src and templates in it. Then I have main in the src folder. So I have this code:

basePath := "templates"
templateFolder, err := os.Open(basePath)
if err != nil {
    log.Fatal(err)
}
defer templateFolder.Close()

I think it has something to do with the basePath that I am using with the open, but I cannot figure out how I need to preface "templates" in order for it to find this directory. I am sure this is an easy fix, but it has me perplexed. Any help would be greatly appreciated.

答案1

得分: 4

根据我们在评论中的讨论,问题是由应用程序在错误的工作目录中运行引起的。

修复方法是修改路径,如下所示:

basePath := "../../templates"

您还可以使用os.Chdir来永久更改工作目录(在进程的持续时间内),而不使用../..。更多信息请参考:https://golang.org/pkg/os/#File.Chdir

英文:

Per our discussion in the comments, it turned out that the issue was caused by the application running in an incorrect working directory.

The fix was to modify the path, as such:

basePath := "../../templates"

You can also use os.Chdir to change the working directory permanently (for the duration of the process), and avoid using the ../... More info here: https://golang.org/pkg/os/#File.Chdir

huangapple
  • 本文由 发表于 2015年11月24日 11:59:29
  • 转载请务必保留本文链接:https://go.coder-hub.com/33885208.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定