英文:
How do I create crossplatform file paths in Go?
问题
我想在golang中打开一个给定的文件"directory/subdirectory/file.txt"
。有没有一种推荐的方式以操作系统无关的方式来表示这样的路径(即在Windows中使用反斜杠,在Mac和Linux中使用正斜杠)?类似于Python的os.path
模块?
英文:
I want to open a given file "directory/subdirectory/file.txt"
in golang. What is the recommended way to express such a path in an OS agnostic way (ie backslashes in Windows, forward slashes in Mac and Linux)? Something like Python's os.path
module?
答案1
得分: 84
要直接创建和操作特定于操作系统的路径,请使用os.PathSeparator
和path/filepath
包。
另一种方法是始终在程序中使用'/'
和path
包。path
包使用'/'
作为路径分隔符,不考虑操作系统。在打开或创建文件之前,通过调用filepath.FromSlash(path string)
将以/
分隔的路径转换为特定于操作系统的路径字符串。通过调用filepath.ToSlash(path string)
可以将操作系统返回的路径转换为以/
分隔的路径。
英文:
For creating and manipulating OS-specific paths directly use os.PathSeparator
and the path/filepath
package.
An alternative method is to always use '/'
and the path
package throughout your program. The path
package uses '/'
as path separator irrespective of the OS. Before opening or creating a file, convert the /-separated path into an OS-specific path string by calling filepath.FromSlash(path string)
. Paths returned by the OS can be converted to /-separated paths by calling filepath.ToSlash(path string)
.
答案2
得分: 47
使用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)
}
Go Playground: https://go.dev/play/p/2Fpb_vJzvSb
英文:
Use path/filepath
instead of path
. path
is intended for forward slash-separated paths only (such as those used in URLs), while path/filepath
manipulates paths across different operating systems.
Example:
package main
import (
"fmt"
"path/filepath"
)
func main() {
path := filepath.Join("home", "hello", "world.txt")
fmt.Println(path)
}
Go Playground: https://go.dev/play/p/2Fpb_vJzvSb
答案3
得分: 22
根据@EvanShaw的回答和这篇博客,创建了以下代码:
package main
import (
"fmt"
"os"
"path/filepath"
)
func main() {
p := filepath.FromSlash("path/to/file")
fmt.Println("Path: " + p)
}
返回:
Path: path\to\file
在Windows上。
1: https://golangcode.com/cross-platform-file-paths/
英文:
Based on the answer of @EvanShaw and this blog the following code was created:
package main
import (
"fmt"
"os"
"path/filepath"
)
func main() {
p := filepath.FromSlash("path/to/file")
fmt.Println("Path: " + p)
}
returns:
Path: path\to\file
on Windows.
1: https://golangcode.com/cross-platform-file-paths/
答案4
得分: -5
Go将正斜杠(/
)视为在所有平台上的通用分隔符1。无论运行时操作系统如何,"directory/subdirectory/file.txt"
都将被正确打开。
英文:
Go treats forward slashes (/
) as the universal separator across all platforms [1]. "directory/subdirectory/file.txt"
will be opened correctly regardless of the runtime operating system.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论