Swiftorial Logo
Home
Swift Lessons
Matchups
CodeSnaps
Tutorials
Career
Resources

Working with Directories in Go

Introduction

In Go, working with directories is a common task when dealing with file systems. This tutorial will guide you through the essential operations for handling directories using the Go programming language. We will cover creating, reading, and deleting directories, as well as listing directory contents.

Creating a Directory

To create a directory in Go, you can use the os.Mkdir or os.MkdirAll functions. The os.Mkdir function creates a single directory, while os.MkdirAll can create a directory along with any necessary parents.

Example:

package main

import (
    "fmt"
    "os"
)

func main() {
    err := os.Mkdir("exampleDir", 0755)
    if err != nil {
        fmt.Println(err)
    } else {
        fmt.Println("Directory created successfully")
    }
}

Output:

Directory created successfully

Reading a Directory

To read the contents of a directory, you can use the os.Open function to open the directory and the Readdir method to list its contents.

Example:

package main

import (
    "fmt"
    "os"
)

func main() {
    dir, err := os.Open(".")
    if err != nil {
        fmt.Println(err)
        return
    }
    defer dir.Close()

    files, err := dir.Readdir(0)
    if err != nil {
        fmt.Println(err)
        return
    }

    for _, file := range files {
        fmt.Println(file.Name())
    }
}

Output:

file1.txt
file2.txt
exampleDir
                

Deleting a Directory

To delete a directory, you can use the os.Remove or os.RemoveAll functions. The os.Remove function deletes a single directory, while os.RemoveAll deletes a directory and its contents recursively.

Example:

package main

import (
    "fmt"
    "os"
)

func main() {
    err := os.Remove("exampleDir")
    if err != nil {
        fmt.Println(err)
    } else {
        fmt.Println("Directory deleted successfully")
    }
}

Output:

Directory deleted successfully

Listing Directory Contents

To list the contents of a directory, you can use the ioutil.ReadDir function, which returns a list of directory entries sorted by filename.

Example:

package main

import (
    "fmt"
    "io/ioutil"
)

func main() {
    files, err := ioutil.ReadDir(".")
    if err != nil {
        fmt.Println(err)
        return
    }

    for _, file := range files {
        fmt.Println(file.Name())
    }
}

Output:

file1.txt
file2.txt
exampleDir