How to check if a directory exists in Golang

In this example, we show how to check if a directory exists in Golang.

The IsNotExist returns a boolean value indicating whether the error is known to report that a file or directory does not exist.

How to check if a directory exists in Golang

In the example, we create a directory if it does not exists. If it exists, we print a message.

Let's create a file named go_example.go and add the following content to it:

package main

import (
    "fmt"
    "os"
)

func main() {

    path := "demo"

    if _, err := os.Stat(path); os.IsNotExist(err) {

        os.Mkdir(path, 0755)
        fmt.Println("Directory created")
    } else {

        fmt.Println("Directory already exists")
    }
}

Output:

G:\GoLang\examples>go run go_example.go
Directory already exists

Let's see how to create a new directory if it does not exist:

package main

import (
    "fmt"
    "os"
)

func main() {

    path := "demo1"

    if _, err := os.Stat(path); os.IsNotExist(err) {

        os.Mkdir(path, 0755)
        fmt.Println("Directory created")
    } else {

        fmt.Println("Directory already exists")
    }
}

Output:

G:\GoLang\examples>go run go_example.go
Directory created

Comments