Go - create, rename and delete directory examples

In this example, we demonstrate how to create, rename and delete the directory in Golang with examples.

Go - create a directory with os.Mkdir

The os.Mkdir creates a new directory with the specified name and permission bits.

The example creates a directory named demo. The 0755 means read and execute access for everyone and also write access for the owner of the file.

package main

import (
    "log"
    "os"
)

func main() {

	path := "demo"
	
    err := os.Mkdir(path, 0755)

    if err != nil {
        log.Fatal(err)
    }
}

Output:

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

Go rename directory with os.Rename

The Rename function renames (moves) a source to a destination.

The example renames a directory demo to demo1.

package main

import (
    "fmt"
    "log"
    "os"
)

func main() {

    oldpath := "demo"
    newpath := "demo1"

    err := os.Rename(oldpath, newpath)

    if err != nil {
        log.Fatal(err)
    }

    fmt.Println("directory renamed")
}

Output:

G:\GoLang\examples>go run go_example.go
directory renamed

Go - delete a directory with os.Remove

With the os.Remove function, we remove a single directory; the directory must be empty.

The example removes an empty demo1 directory.


package main

import (
    "log"
    "os"
)

func main() {

    err := os.Remove("demo1")

    if err != nil {
        log.Fatal(err)
    }
}

Output:

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

Comments