Golang os.Create 带有嵌套目录的路径

Exi*_*ind 0 operating-system go

正如 GoDocs 中提到的,os.Create()在特定路径中创建一个文件。

os.Create("fonts/foo/font.eot")
Run Code Online (Sandbox Code Playgroud)

但是当fontsfoo不存在时,它返回panic: open fonts/foo/font.eot: The system cannot find the path specified.
所以我用来os.MkdirAll()创建嵌套目录。但是这个功能还有很多其他的问题。

path := "fonts/foo/font.eot"
// this line create a directory named (font.eot) !
os.MkdirAll(path, os.ModePerm)
Run Code Online (Sandbox Code Playgroud)

有没有更好的方法在嵌套目录中创建文件?

小智 13

标准的方法是这样的:

func create(p string) (*os.File, error) {
    if err := os.MkdirAll(filepath.Dir(p), 0770); err != nil {
        return nil, err
    }
    return os.Create(p)
}
Run Code Online (Sandbox Code Playgroud)

一些注意事项:

  • os.Create 不会像问题中所说的那样恐慌。
  • 从文件路径的目录部分创建一个目录,而不是完整路径。