如何在 Go 中创建跨平台文件路径?

问题描述 投票:0回答:4

我想在 golang 中打开给定的文件

"directory/subdirectory/file.txt"
。以与操作系统无关的方式表达此类路径的推荐方法是什么(即 Windows 中的反斜杠,Mac 和 Linux 中的正斜杠)?类似于 Python 的
os.path
模块?

file io directory go
4个回答
90
投票

要创建和操作特定于操作系统的路径,请直接使用

os.PathSeparator
path/filepath
包。

另一种方法是在整个程序中始终使用

'/'
path
包。
path
包使用
'/'
作为路径分隔符,与操作系统无关。在打开或创建文件之前,请通过调用
filepath.FromSlash(path string)
将 / 分隔的路径转换为操作系统特定的路径字符串。操作系统返回的路径可以通过调用
filepath.ToSlash(path string)
.

转换为 / 分隔的路径

53
投票

使用

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)
}

去游乐场:https://go.dev/play/p/2Fpb_vJzvSb


24
投票

根据@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

-5
投票

Go 将正斜杠 (

/
) 视为跨所有平台的通用分隔符 [1]。无论运行时操作系统如何,
"directory/subdirectory/file.txt"
都将正确打开。

© www.soinside.com 2019 - 2024. All rights reserved.