在 Go 中获取当前路径的方法有两种:使用 os.Getwd 返回当前工作目录的绝对路径。使用 path/filepath.Abs 返回指定路径的绝对路径,即使指定了相对路径。

在 Go 中获取当前路径
在 Go 中获取当前路径有两种方法:
1. 使用 os.Getwd
package main
import (
"fmt"
"os"
)
func main() {
wd, err := os.Getwd()
if err != nil {
fmt.Println(err)
return
}
fmt.Println("Current working directory:", wd)
}2. 使用 path/filepath.Abs
立即学习“go语言免费学习笔记(深入)”;
package main
import (
"fmt"
"path/filepath"
)
func main() {
wd, err := filepath.Abs(".")
if err != nil {
fmt.Println(err)
return
}
fmt.Println("Current working directory:", wd)
}示例输出:
Current working directory: /Users/username/projects/my_project
解释:
-
os.Getwd函数返回当前工作目录的绝对路径。 -
path/filepath.Abs函数返回指定路径的绝对路径。在我们的例子中,.代表当前目录。
注意事项:
- 如果没有设置工作目录,
os.Getwd将返回 ""。 -
path/filepath.Abs返回的路径始终是绝对路径,即使指定了相对路径。










