问题引入
我们在操作Golang文件时用os包进行Open,Create等操作的时候,需要传入一个path
这个path可以是绝对路径,也可以是相对路径
深入思考
./test.txt
file, err := os.Open("./test.txt")
if err != nil {
fmt.Println("open file failed:", err)
}
//输出文件
fmt.Printf("file = %v\n", file)
//关闭文件
err = file.Close()
output:
open file failed: open ./test.txt: The system cannot find the file specified.
file = <nil>
问题解决
当使用Goland右键运行时:
./是你当前的工程目录,也就是GOPATH的目录,并不是该 go 文件所对应的目录
os.Open("./test.txt")//E:\\Code\\GoDemo\\test.txt
os.Open("./src/test.txt")//E:\\Code\\GoDemo\\src\\test.txt
os.Open("./src/go_code/test.txt")//E:\\Code\\GoDemo\\src\\go_code\\test.txt
os.Open("./src/go_code/project_09/main/test.txt")//E:\\Code\\GoDemo\\src\\go_code\\project_09\\main\\test.txt
当使用terminal运行时
./就是当前文件所在目录