戈朗操作系统.创建具有嵌套目录的路径



如GoDocs中所述,os.Create()在特定路径中创建一个文件。

os.Create("fonts/foo/font.eot")

但是当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)

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

标准方式是这样的:

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

一些注意事项:

  • 操作系统。创建不会像问题中所述的那样惊慌失措。
  • 从文件路径的目录部分(而不是完整路径(创建目录。

最新更新