我想在 golang 中打开给定的文件
"directory/subdirectory/file.txt"
。以与操作系统无关的方式表达此类路径的推荐方法是什么(即 Windows 中的反斜杠,Mac 和 Linux 中的正斜杠)?类似于 Python 的 os.path
模块?
os.PathSeparator
和 path/filepath
包。
另一种方法是在整个程序中始终使用
'/'
和 path
包。 path
包使用 '/'
作为路径分隔符,与操作系统无关。在打开或创建文件之前,请通过调用 filepath.FromSlash(path string)
将 / 分隔的路径转换为操作系统特定的路径字符串。操作系统返回的路径可以通过调用 filepath.ToSlash(path string)
. 转换为 / 分隔的路径
path/filepath
而不是 path
。 path
仅适用于正斜杠分隔的路径(例如 URL 中使用的路径),而 path/filepath
则可以跨不同操作系统操作路径。
示例:
package main
import (
"fmt"
"path/filepath"
)
func main() {
path := filepath.Join("home", "hello", "world.txt")
fmt.Println(path)
}
根据@EvanShaw 的回答和此博客创建了以下代码:
package main
import (
"fmt"
"os"
"path/filepath"
)
func main() {
p := filepath.FromSlash("path/to/file")
fmt.Println("Path: " + p)
}
在 Windows 上它将返回:
Path: path\to\file