英文:
Is it possible to get a file without knowing its extension?
问题
我需要获取一个已知路径和名称的文件,即使我不知道它的扩展名。
例如:
fileBytes, err := ioutil.ReadFile("./test.txt")
可以工作。
但是
fileBytes, err := ioutil.ReadFile("./test")
不行。
英文:
I need to get a file with a known path and name, even though I don't know exactly its extension
for example:
fileBytes, err := ioutil.ReadFile("./test.txt")
works.
but
fileBytes, err := ioutil.ReadFile("./test")
don't
答案1
得分: 2
假设这段代码是用于一个通用的库,其中可能还有其他基于前缀的功能,我可能会这样设计它:
package prefixpath
var (
ErrNoMatch = errors.New("prefixpath: 没有匹配项")
ErrMultiple = errors.New("prefixpath: 多个匹配项")
)
func ReadFirst(prefix string) ([]byte, error) {
paths, err := filepath.Glob(prefix + ".*")
if err != nil {
return nil, err
}
if len(paths) == 0 {
return nil, ErrNoMatch
}
if len(paths) > 1 {
return nil, ErrMultiple
}
return ioutil.ReadFile(paths[0])
}
然后对于你的原始代码:
data, err := prefixpath.ReadFirst("./test") // 省略了导入 prefixpath 包
英文:
Assuming this code was for a general purpose library where there might be other prefix-based functionality, I might model it like this:
package prefixpath
var (
ErrNoMatch = errors.New("prefixpath: no matches")
ErrMultiple = errors.New("prefixpath: more than one match")
)
func ReadFirst(prefix string) ([]byte, error) {
paths, err := filepath.Glob(prefix + ".*")
if err != nil {
return nil, err
}
if len(paths) == 0 {
return nil, ErrNoMatch
}
if len(paths) > 1 {
return nil, ErrMultiple
}
return ioutil.ReadFile(paths[0])
}
Then for your original code:
data, err := prefixpath.ReadFirst("./test") // import of package prefixpath omitted
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论