Cookies management by TermsFeed Cookie Consent

📁 Create a directory in Go

introduction file

To create a single directory in Go, use the os.Mkdir() function. If you want to create a hierarchy of folders (nested directories), use os.MkdirAll(). Both functions require a path and permission bits of the folder as arguments.

In the examples below, we use the os.ModePerm constant as permission bits which is equivalent to 0777. For directories in Unix-like systems, it means that a user has rights to list, modify and search files in the directory.

Create a single directory

package main

import (
    "log"
    "os"
)

func main() {
    if err := os.Mkdir("a", os.ModePerm); err != nil {
        log.Fatal(err)
    }
}

The os.Mkdir() creates a new directory with the specified name, but cannot create subdirectories. For example, if you use os.Mkdir() with "a/b/c/d" as a name argument:

os.Mkdir("a/b/c/d", os.ModePerm)

you get the error:

mkdir a/b/c/d: no such file or directory

Create a hierarchy of directories (nested directories)

package main

import (
    "log"
    "os"
)

func main() {
    if err := os.MkdirAll("a/b/c/d", os.ModePerm); err != nil {
        log.Fatal(err)
    }
}

The os.MkdirAll() creates a given directory, along with any necessary parent folder. Use this function if you need to create a nested hierarchy of directories in your program.


Thank you for being on our site 😊. If you like our tutorials and examples, please consider supporting us with a cup of coffee and we'll turn it into more great Go examples.

Have a great day!

Buy Me A Coffee

📎 Convert JSON to CSV in Go

Learn how to transform JSON file to CSV
introduction file json csv

⌛ Temporary file in Go - how to create?

Learn how to create and use a temporary file or folder
introduction file

🔄 Convert CSV to JSON in Go

Learn how to transform CSV file data to JSON
introduction file csv json