@JimB and @m-szalik write good answers and advices. That looks good enough to solve your problem.
But I try to summarize the answers in my style.
Summary
你们需要把投入文件放在与汇编和执行的双亲档案工作目录一致的名录中,而不是放在你发展环境的目录上。
您可在以下档案等级中使用<代码>。 重要的是将执行你的双手。
// run main at ./src
➜ src ./main
// file hierarchy
.
├── data
│ ├── example.csv
│ └── output.csv
└── src
├── main
└── main.go
Definitions we have to know
简言之,relative path
取决于 工作名录
,其中your汇编并实施了双亲文件
。
Therefore, JimB said the compiled binary
matters.
Absolute path
“asolute or full path >在档案系统中指明了同一地点,而不论目前的工作名录如何。 为此,它必须包括根基。
Relative path
By contrast, a relative path starts from some given working directory,
...
https://en.wikipedia.org/wiki/Path_(computing)#Absolute_and_relative_paths
Working directory
在计算时,工艺目录()是等级档案系统的目录,如果与这一过程有动态关系的话。 有时称为目前的工作名录。
https://en.wikipedia.org/wiki/Working_directory
Simplified example
package main
import (
"encoding/json"
"fmt"
"os"
)
type Human struct {
Life string `json:"life"`
}
func main() {
var human Human
data, errRead := os.ReadFile("txt/input")
errUnMarshall := json.Unmarshal(data, &human)
fmt.Println(errRead)
fmt.Println(errUnMarshall)
fmt.Println(human)
}
This code reads input
text from its relative path txt/
And its directories and files are like this.
.
└── src
├── main
├── main.go
└── txt
└── input
Case 1
I run main
on src/
. Then it works.
The reason is main
s working directory src/
and it corresponds with os.ReadFile("txt/input")
它照此印刷。 。
➜ src ./main
<nil>
<nil>
{Life is hard}
Case 2
I run main
on .
. Then it fails.
The reason is main
s working directory .
and it doesn t correspond with os.ReadFile("txt/input")
➜ . ./src/main
open txt/input: no such file or directory
unexpected end of JSON input
{}
Etc
您可以发现,工作名录是您的双亲在终点站的名录。 重要的是该方案的指南。
If you re using IDE such as IntelliJ, then you can set the working directory at Run/Debug configuration.