Sling Academy
Home/Golang/How to list all files and subfolders in a folder in Go

How to list all files and subfolders in a folder in Go

Last updated: November 26, 2024

In Go, listing all files and subfolders within a given directory can be achieved using the standard library. This tutorial will demonstrate how to accomplish this task efficiently.

Using the filepath package

The filepath package provides utilities for manipulating filename paths. To list files and directories, we can use the Walk function of the filepath package.

package main

import (
    "fmt"
    "log"
    "os"
    "path/filepath"
)

func main() {
    root := "./your_directory_path"
    err := filepath.Walk(root, func(path string, info os.FileInfo, err error) error {
        if err != nil {
            log.Println(err)
            return err
        }
        fmt.Println(path)
        return nil
    })
    if err != nil {
        log.Fatal(err)
    }
}

Replace "./your_directory_path" with the actual path of the directory you want to inspect. This code will traverse every file and directory starting from the specified root, printing out each path.

Explanation of the Walk Function

The filepath.Walk function takes two arguments:

  • root: The root directory from which to start walking.
  • walkFn: A callback function that's called for every file or directory in the tree.

The walkFn takes three parameters:

  • path: The current path being visited.
  • info: An os.FileInfo object that contains information about the file or directory.
  • err: Any error encountered during the walking process.

If your callback handles an error and wishes to stop further processing, returning the error will abort the walk.

Using os and ioutil packages

Alternatively, you can use a combination of the os and io/ioutil packages for manual directory walking:

package main

import (
    "fmt"
    "io/ioutil"
    "log"
    "os"
)

func ListDir(dir string) {
    files, err := ioutil.ReadDir(dir)
    if err != nil {
        log.Fatal(err)
    }

    for _, file := range files {
        fmt.Println(filepath.Join(dir, file.Name()))
        if file.IsDir() {
            ListDir(filepath.Join(dir, file.Name()))
        }
    }
}

func main() {
    ListDir("./your_directory_path")
}

This recursive function lists all files and directories by reading the directory content using ioutil.ReadDir, and then recursively calling itself for every subdirectory.

Conclusion

Listing files and directories in Go can be easily achieved using the built-in filepath or os and io/ioutil packages. Depending on your preference for usage and efficiency, you can choose either approach to implement directory listing in your Go applications.

Next Article: How to zip/ unzip a file or folder in Go

Previous Article: How to read and parse XML files in Go

Series: File I/O and Operating System Interaction

Golang

Related Articles

You May Also Like

  • How to remove HTML tags in a string in Go
  • How to remove special characters in a string in Go
  • How to remove consecutive whitespace in a string in Go
  • How to count words and characters in a string in Go
  • Relative imports in Go: Tutorial & Examples
  • How to run Python code with Go
  • How to generate slug from title in Go
  • How to create an XML sitemap in Go
  • How to redirect in Go (301, 302, etc)
  • Using Go with MongoDB: CRUD example
  • Auto deploy Go apps with CI/ CD and GitHub Actions
  • Fixing Go error: method redeclared with different receiver type
  • Fixing Go error: copy argument must have slice type
  • Fixing Go error: attempted to use nil slice
  • Fixing Go error: assignment to constant variable
  • Fixing Go error: cannot compare X (type Y) with Z (type W)
  • Fixing Go error: method has pointer receiver, not called with pointer
  • Fixing Go error: assignment mismatch: X variables but Y values
  • Fixing Go error: array index must be non-negative integer constant