英文:
Opening a File from a FileInfo
问题
在golang中,如果我有一个os.FileInfo
,是否有办法从中打开一个*os.File
,而不需要原始路径?
假设我有这样的代码:
package main
import (
"os"
"path/filepath"
"strings"
)
var files []os.FileInfo
func walker(path string, info os.FileInfo, err error) error {
if strings.HasSuffix(info.Name(), ".txt") {
files = append(files, info)
}
return nil
}
func main() {
err := filepath.Walk("/tmp/foo", walker)
if err != nil {
println("Error", err)
} else {
for _, f := range files {
println(f.Name())
// 这里我们想要打开文件
}
}
}
是否有办法将FileInfo
转换为*File
?我实际上使用的代码不是基于filepath.Walk
,但我确实得到了一个[]os.FileInfo
切片。我仍然有根目录和文件名,但似乎在这个阶段已经丢失了任何进一步的子树信息。
英文:
In golang, if I have an os.FileInfo
, is there any way to open an *os.File
from that by itself without the original path?
Let's say I had something like this:
package main
import (
"os"
"path/filepath"
"strings"
)
var files []os.FileInfo
func walker(path string, info os.FileInfo, err error) error {
if strings.HasSuffix(info.Name(), ".txt") {
files = append(files, info)
}
return nil
}
func main() {
err := filepath.Walk("/tmp/foo", walker)
if err != nil {
println("Error", err)
} else {
for _, f := range files {
println(f.Name())
// This is where we'd like to open the file
}
}
}
Is there a way to convert FileInfo
to * File
? The code I'm actually working with isn't based on filepath.Walk
; but I do get an []os.FileInfo
slice back. I still have the root directory, and the file name, but it seems like any further sub-tree information has gone by this stage.
答案1
得分: 24
不。FileInfo
接口根本不公开路径,而os
和ioutil
包中提供的所有方法都接受路径名作为字符串。
英文:
No. The FileInfo
interface simply does not expose the path and all provided methods in the os
and ioutil
packages accept the pathname as a string.
答案2
得分: 10
附加信息,这是构建包括路径的文件名字符串的方法:
filename := filepath.Join(path, info.Name())
英文:
As additional info, this is how to constructor the filename string including path:
filename := filepath.Join(path, info.Name())
答案3
得分: 4
不,只有 FileInfo 是无法打开文件的。os.Open 只接受字符串作为参数。你应该始终提供文件路径或父路径,因为这是获取 FileInfo 的唯一方式。
英文:
No, a file cannot be opened with just the FileInfo. os.Open only takes a string. You should always have the path or the parent path because that is the only way to get a FileInfo.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论