ZetCode

Go list directory

last modified October 30, 2026 Go 1.27

In this article we show how to list directory contents in Go. We read a single directory with os.ReadDir, inspect the entries, filter and sort them, walk a whole tree with filepath.WalkDir, and match names with filepath.Glob.

All examples in this article were compiled and run with Go 1.27.0.

The demo directory

The examples work with the following tree. It contains one hidden file, two subdirectories and files of several sizes, including a 2048-byte logo.png.

$ find project | sort
project
project/assets
project/assets/logo.png
project/assets/style.css
project/.gitignore
project/notes.txt
project/README.md
project/report.txt
project/src
project/src/main.go
project/src/util.go

The text files are 6 to 31 bytes long, style.css has 43 bytes and the image has 2048 bytes, so the whole tree holds 2204 bytes in eight files.

Listing a directory with os.ReadDir

os.ReadDir returns a slice of fs.DirEntry values sorted by filename. It opens the directory, reads all entries and closes it, so there is no handle to release.

func ReadDir(name string) ([]DirEntry, error)

That is the signature from the os package; the same function exists on fs.FS for embedded and in-memory filesystems.

main.go
package main

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

func main() {

    entries, err := os.ReadDir("project")
    if err != nil {
        log.Fatal(err)
    }

    for _, e := range entries {
        fmt.Printf("%-12s dir=%-5t\n", e.Name(), e.IsDir())
    }
}

The listing includes hidden files and directories, because the function does not filter anything. The order is lexical, so the output is the same on every run.

$ go run main.go
.gitignore   dir=false
README.md    dir=false
assets       dir=true
notes.txt    dir=false
report.txt   dir=false
src          dir=true

Separating files from directories

DirEntry.IsDir reports whether the entry is a directory. It reads a type bit that the operating system already returned with the directory listing, so it does not touch the disk again.

main.go
package main

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

func main() {

    entries, err := os.ReadDir("project")
    if err != nil {
        log.Fatal(err)
    }

    fmt.Println("text files:")

    for _, e := range entries {
        if !e.IsDir() && filepath.Ext(e.Name()) == ".txt" {
            fmt.Println(" ", e.Name())
        }
    }

    fmt.Println("directories:")

    for _, e := range entries {
        if e.IsDir() {
            fmt.Println(" ", e.Name())
        }
    }
}

filepath.Ext returns the suffix starting at the final dot, so the comparison selects only .txt files. The two loops show the two kinds of entries that the example is interested in.

$ go run main.go
text files:
  notes.txt
  report.txt
directories:
  assets
  src

Reading size and modification time

DirEntry.Info returns the fs.FileInfo of the entry, which carries the size, the modification time and the permission bits. The call may read the disk, so it is only made for the entries that need it.

main.go
package main

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

func main() {

    entries, err := os.ReadDir("project")
    if err != nil {
        log.Fatal(err)
    }

    for _, e := range entries {

        if e.IsDir() {
            continue
        }

        info, err := e.Info()
        if err != nil {
            log.Fatal(err)
        }

        fmt.Printf("%-12s %5d %s\n", e.Name(), info.Size(),
            info.ModTime().Format(time.DateOnly))
    }
}

Directories are skipped because their size is filesystem specific: on ext4 a directory usually reports 4096 bytes regardless of its contents. For files the size is exact, and time.DateOnly formats the timestamp as 2025-01-10.

$ go run main.go
.gitignore       6 2025-01-10
README.md       18 2026-06-01
notes.txt       11 2025-01-10
report.txt      18 2025-01-10

Skipping hidden files

On Unix a name that starts with a dot is hidden from ls and from shell globs, but not from os.ReadDir. The check is a plain string prefix test.

main.go
package main

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

func main() {

    entries, err := os.ReadDir("project")
    if err != nil {
        log.Fatal(err)
    }

    var visible, hidden []string

    for _, e := range entries {
        if strings.HasPrefix(e.Name(), ".") {
            hidden = append(hidden, e.Name())
        } else {
            visible = append(visible, e.Name())
        }
    }

    fmt.Println("visible:", visible)
    fmt.Println("hidden: ", hidden)
}

Both slices appear in the order of the directory listing. The same test works on Windows, where the dot convention is a matter of habit rather than of the operating system.

$ go run main.go
visible: [README.md assets notes.txt report.txt src]
hidden:  [.gitignore]

Sorting entries by size

os.ReadDir always sorts by name, so any other order has to be applied explicitly. slices.SortFunc sorts a slice with a three-way comparator, and cmp.Or combines the size comparison with a name comparison that makes the result stable for equal sizes.

main.go
package main

import (
    "cmp"
    "fmt"
    "log"
    "os"
    "slices"
)

type fileEntry struct {
    Name string
    Size int64
}

func main() {

    entries, err := os.ReadDir("project")
    if err != nil {
        log.Fatal(err)
    }

    var files []fileEntry

    for _, e := range entries {
        if e.IsDir() {
            continue
        }
        info, err := e.Info()
        if err != nil {
            log.Fatal(err)
        }
        files = append(files, fileEntry{e.Name(), info.Size()})
    }

    slices.SortFunc(files, func(a, b fileEntry) int {
        return cmp.Or(cmp.Compare(b.Size, a.Size), cmp.Compare(a.Name, b.Name))
    })

    for _, f := range files {
        fmt.Printf("%-12s %5d\n", f.Name, f.Size)
    }
}

The comparison is reversed for the size, which puts the largest files first. Without the second comparison, README.md and report.txt would appear in an unspecified order because both have 18 bytes.

$ go run main.go
README.md       18
report.txt      18
notes.txt       11
.gitignore       6

Walking a tree with WalkDir

filepath.WalkDir visits the root and then every entry below it in lexical order. The callback receives the path, the entry and an error; a nil return continues the walk.

main.go
package main

import (
    "fmt"
    "io/fs"
    "log"
    "path/filepath"
    "strings"
)

func main() {

    root := "project"

    err := filepath.WalkDir(root, func(path string, d fs.DirEntry, err error) error {
        if err != nil {
            return err
        }

        rel, err := filepath.Rel(root, path)
        if err != nil {
            return err
        }

        depth := strings.Count(rel, string(filepath.Separator)) + 1
        name := filepath.Base(path)
        if rel == "." {
            name = root
            depth = 0
        }

        fmt.Printf("%s%s\n", strings.Repeat("  ", depth), name)
        return nil
    })

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

filepath.Rel strips the root, and the number of remaining separators gives the indentation level. The root itself is reported with the relative path ., which is why it is handled separately.

$ go run main.go
project
  .gitignore
  README.md
  assets
    logo.png
    style.css
  notes.txt
  report.txt
  src
    main.go
    util.go

Counting files and summing their sizes

The same walk can accumulate totals. Directories are skipped, and the size of every file is added up.

main.go
package main

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

func main() {

    var total int64
    var count int

    err := filepath.WalkDir("project", func(path string, d fs.DirEntry, err error) error {
        if err != nil {
            return err
        }
        if d.IsDir() {
            return nil
        }

        info, err := d.Info()
        if err != nil {
            return err
        }

        total += info.Size()
        count++
        return nil
    })

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

    fmt.Printf("%d files, %d bytes\n", count, total)
}

The number can be compared with du -s project, which reports 44 KiB here: the filesystem allocates whole 4 KiB blocks, so eight small files occupy far more space than their logical sizes. du -sb project prints 14492 bytes, because it adds the apparent size of the three directories (4096 bytes each) to the 2204 bytes of the files.

$ go run main.go
8 files, 2204 bytes

Matching names with Glob

filepath.Glob matches a pattern against existing paths. The wildcard * matches any sequence of characters except a separator, so it never descends into a subdirectory.

main.go
package main

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

func main() {

    patterns := []string{
        "project/*.txt",
        "project/*/*.go",
        "project/**/*.txt",
        "project/**/*.go",
    }

    for _, pattern := range patterns {
        matches, err := filepath.Glob(pattern)
        if err != nil {
            log.Fatal(err)
        }
        fmt.Printf("%-18s %v\n", pattern, matches)
    }
}

The third pattern returns nothing: ** has no special meaning in Go and behaves like a single *, so it only matches names directly inside project. The fourth pattern matches the two files in src for the same reason, not because it recursed. Use WalkDir for recursive searches.

$ go run main.go
project/*.txt      [project/notes.txt project/report.txt]
project/*/*.go     [project/src/main.go project/src/util.go]
project/**/*.txt   []
project/**/*.go    [project/src/main.go project/src/util.go]

Reading in batches with File.ReadDir

The method (*os.File).ReadDir reads at most n entries per call and returns io.EOF after the last batch. It exists for very large directories where holding every entry in memory is wasteful.

main.go
package main

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

func main() {

    f, err := os.Open("project")
    if err != nil {
        log.Fatal(err)
    }
    defer f.Close()

    for {
        batch, err := f.ReadDir(3)
        if err == io.EOF {
            break
        }
        if err != nil {
            log.Fatal(err)
        }

        for _, e := range batch {
            fmt.Println(e.Name())
        }
        fmt.Println("--- batch of", len(batch))
    }
}

Unlike the package-level function, the method does not sort: the names arrive in the order the filesystem returns them. A program that needs sorted output must collect the entries and sort them, or use os.ReadDir.

$ go run main.go
README.md
assets
.gitignore
--- batch of 3
notes.txt
src
report.txt
--- batch of 3

Handling a missing directory

A failed ReadDir returns an empty slice and a *fs.PathError. The error wraps fs.ErrNotExist, so errors.Is distinguishes a missing directory from a permission problem.

main.go
package main

import (
    "errors"
    "fmt"
    "io/fs"
    "os"
)

func main() {

    entries, err := os.ReadDir("nope")
    fmt.Println(len(entries), err)
    fmt.Println(errors.Is(err, fs.ErrNotExist))

    var pe *fs.PathError
    fmt.Println(errors.As(err, &pe), pe.Op, pe.Path)
}

errors.As fills in the concrete error value, which exposes the operation and the path that failed. The same handling works for WalkDir, whose callback receives the error for a subdirectory it could not read.

$ go run main.go
0 open nope: no such file or directory
true
true open nope

Symbolic links

A symlink is reported as an entry of its own. IsDir is false for a link to a directory, the link target is read with os.Readlink, and DirEntry.Type has the fs.ModeSymlink bit set.

main.go
package main

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

func main() {

    entries, err := os.ReadDir("links")
    if err != nil {
        log.Fatal(err)
    }

    for _, e := range entries {

        kind := "file"
        switch {
        case e.Type()&fs.ModeSymlink != 0:
            kind = "symlink"
        case e.IsDir():
            kind = "dir"
        }

        target, err := os.Readlink("links/" + e.Name())
        if err != nil {
            target = "-"
        }

        fmt.Printf("%-15s %-8s -> %s\n", e.Name(), kind, target)
    }
}

The links directory contains a link to a file, a link to a directory and a broken link. All three are listed, because a directory listing does not follow or validate the targets.

$ go run main.go
broken.txt      symlink  -> missing.txt
notes-link.txt  symlink  -> ../project/notes.txt
src-link        symlink  -> ../project/src

Source

Go os package - reference

In this article we have listed directory contents with os.ReadDir, inspected entry metadata, filtered and sorted the results, walked a tree with filepath.WalkDir, matched names with filepath.Glob and handled symlinks and missing directories.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all Go tutorials.