What's the most idiomatic way to create directories recursivelly in Go?

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

What's the most idiomatic way to create directories recursivelly in Go?

问题

我需要使用Go创建给定的嵌套目录结构,但是我无法找到最实用和惯用的方法来实现这一点。以下是一些灵感:

Bash:mkdir -p some/deep/path

C#:IO.Directory.CreateDirectory(@"some/deep/path")

PHP:mkdir("some/deep/path", 0777, true)

Java:new File("some/deep/path").mkdirs()

Go:?

要求是如果路径已经存在,则操作应该保持静默(就像其他语言示例中一样)。

英文:

I need to create a given nested directory structure using Go, but I couldn't figure out the most practical and idiomatic way to do that. Some inspiration:

Bash: mkdir -p some/deep/path

C# : IO.Directory.CreateDirectory(@"some/deep/path")

PHP : mkdir("some/deep/path", 0777, true)

Java: new File("some/deep/path").mkdirs()

Go : ?

Requirement is that operation should be silent if path is already in place (just like in the other language examples).

答案1

得分: 3

你可以尝试使用os.MkdirAll来创建你所需的所有文件夹。

> MkdirAll会创建一个名为path的目录,连同所有必要的父目录,并返回nil,否则返回一个错误。
权限位perm将用于MkdirAll创建的所有目录。
如果path已经是一个目录,MkdirAll不会执行任何操作并返回nil

可以查看它的test类

请注意,当你查看它的实现时,MkdirAll并不完全是“原子”的。

英文:

You can try and see if os.MkdirAll does create all the folder that you need.

> MkdirAll creates a directory named path, along with any necessary parents, and returns nil, or else returns an error.
The permission bits perm are used for all directories that MkdirAll creates.
If path is already a directory, MkdirAll does nothing and returns nil.

See its test class.

Note that, when you look at its implementation, MkdirAll isn't exactly "atomic".

huangapple
  • 本文由 发表于 2014年12月8日 14:34:39
  • 转载请务必保留本文链接:https://go.coder-hub.com/27352608.html
匿名

发表评论

匿名网友

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

确定