Cookies management by TermsFeed Cookie Consent
Russia has invaded Ukraine and already killed tens of thousands of civilians, with many more raped or tortured. It's a genocide. We need your help. Let's fight back against the Russian regime.
Help Ukraine! Fight the Russian regime!

📁 Create a directory in Go

introduction file

Please consider supporting us by disabling your ad blocker

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.

📎 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