Skip to main content
  1. Tutorials/

📁 List files in a directory in Go

·2 mins

The Go standard library has many functions that allow listing files in a folder. You can list only top-level content of a folder or go through all files and directories recursively in a nested directory structure, as well as list files matching a specific pattern.

In all examples we use a folder tree:

testFolder
├── file1.go
├── file2.txt
└── folder1
    └── fileInFolder1.txt

List files in a directory by using ioutil.ReadDir #

Use ioutil.ReadDir when you want to retrieve files at the top-level of the directory tree.

package main

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

func main() {
    files, err := ioutil.ReadDir("testFolder")
    if err != nil {
        log.Fatal(err)
    }

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

Output:

file1.go
file2.txt
folder1

List files in a directory by using os.File.Readdir #

The function os.File.Readdir works in the same way as ioutil.ReadDir, but it does not sort the result list by name.

package main

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

func main() {
    dir, err := os.Open("testFolder")
    if err != nil {
        log.Fatal(err)
    }

    files, err := dir.Readdir(-1)
    if err != nil {
        log.Fatal(err)
    }

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

Output:

file2.txt
file1.txt
folder1

List files recursively by using filepath.Walk #

Go provides a convenient function filepath.Walk(root string, fn WalkFunc) error to list files recursively. It starts at the root folder and calls fn WalkFunc function for each file and directory in the tree, in lexical order.

package main

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

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

Output:

testFolder
testFolder/file1.go
testFolder/file2.txt
testFolder/folder1
testFolder/folder1/fileInFolder1.txt

List files that match given pattern by using filepath.Glob #

If you are interested only in files that match a given pattern, you can use filepath.Glob, for example, to list all files with .go extension 🙂. Pattern syntax can be found here.

package main

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

func main() {
    files, err := filepath.Glob("testFolder/*.go")
    if err != nil {
        log.Fatal(err)
    }

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

Output:

testFolder/file1.go