如何在Golang中使用Mkdir创建嵌套目录? [英] How to create nested directories using Mkdir in Golang?

查看:1771
本文介绍了如何在Golang中使用Mkdir创建嵌套目录?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图从一个Go可执行文件(如'dir1 / dir2 / dir3')创建一组嵌套目录。

  os.Mkdir(。+ string(filepath.Separator) )+ c.Args()。First(),0777); 

但我不知道如何在该目录内创建预定义的嵌套目录集, Google Fu没有我想象的那么强大。 os.Mkdir 用于创建单个目录。要创建文件夹路径,请使用:

  os.MkdirAll(folderPath,os.ModePerm); 

Go文档


func MkdirAll(路径字符串,perm FileMode)错误

MkdirAll会创建一个名为path的目录以及任何必要的父项,并返回nil,否则返回错误。许可位perm用于MkdirAll创建的所有目录。如果path已经是一个目录,MkdirAll什么也不做,并返回nil。


编辑:



已更新为正确使用 os.ModePerm ,而不是。

对于文件路径的连接,请使用package path / filepath ,如@Chris的答案中所述。

I'm trying to create a set of nested directories from a Go executable such as 'dir1/dir2/dir3'. I've succeeded in creating a single directory with this line:

os.Mkdir("." + string(filepath.Separator) + c.Args().First(),0777);

But I have no idea how to approach creating a predetermined nested set of directories inside of that directory and my Google Fu isn't as strong as I thought it was.

Thanks in advance!

解决方案

os.Mkdir is used to create a single directory. To create a folder path, instead try using:

os.MkdirAll(folderPath, os.ModePerm);

Go documentation

func MkdirAll(path string, perm FileMode) error

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.

Edit:

Updated to correctly use os.ModePerm instead.
For concatenation of file paths, use package path/filepath as described in @Chris' answer.

这篇关于如何在Golang中使用Mkdir创建嵌套目录?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆