使用Go打开需要字符转义的文件路径

huangapple go评论98阅读模式
英文:

Open file with path needing character escaping in Go

问题

我有一个文件,os.open() 返回给我一个 no such file or directory 的错误。有没有一个函数可以转义文件名,以获取正确的路径?类似于 net 包中的 QueryEscape 函数,但当然是用于文件路径。

这是路径名:"Music/3OH!3 - Streets Of Gold 2010 [Cov+CD][Bubanee]/06. Touchin On My - 30H!3.mp3"

我只是使用一个简单的代码:

srcName := "Music/3OH!3 - Streets Of Gold 2010 [Cov+CD][Bubanee]/06. Touchin On My - 30H!3.mp3"
src, err := os.Open(srcName)
if err != nil {
	fmt.Println(err)
	return
}

顺便说一下,文件是存在的,只是路径名无法被正确解析。Bash 可以解析的路径是 Music/3OH\!3\ -\ Streets\ Of\ Gold\ \[Cov+CD\]\[Bubanee\]/12.\ Strrets\ Of\ Gold\ -\ 30H\!3.mp3,其中显示了所有需要转义的字符。

英文:

I have a file which os.open() gives me back, no such file or directory. Is there a function which can escape a file name for getting the correct path to it? Something similar to the net package QueryEscape ?, but for file paths of course

Here is the Path name "Music/3OH!3 - Streets Of Gold 2010 [Cov+CD][Bubanee]/06. Touchin On My - 30H!3.mp3"

I'm just using a simple

srcName := "Music/3OH!3 - Streets Of Gold 2010 [Cov+CD][Bubanee]/06. Touchin On My - 30H!3.mp3"
src, err := os.Open(srcName)
if err != nil {
	fmt.Println(err)
	return
}

The file does exist btw, go just cant follow the path name. The path that bash can follow is Music/3OH\!3\ -\ Streets\ Of\ Gold\ \[Cov+CD\]\[Bubanee\]/12.\ Strrets\ Of\ Gold\ -\ 30H\!3.mp3 which shows all the escaping that is needed.

答案1

得分: 3

我在我的机器上(Mac OS 10.8.3)尝试创建相同的目录结构,并且使用你的代码没有问题打开文件。这意味着在打开时路径已经正确转义。

确保你从Music/文件夹的上一级位置运行你的Go程序,或者只使用完整的根路径作为srcName

英文:

I tried creating the same directory structure on my machine (Mac OS 10.8.3), and I had no trouble opening the file using your code. This means that the path is properly escaped when opening already.

Make sure you're running your go program from a location right above the Music/ folder, or just use the full root path for srcName.

huangapple
  • 本文由 发表于 2013年3月30日 02:26:08
  • 转载请务必保留本文链接:https://go.coder-hub.com/15709178.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定