List all files (recursively) in a directory

Directory listing

Use the ioutil.ReadDir function in package io/ioutil. It returns a sorted slice containing elements of type os.FileInfo.

The code in this example prints a sorted list of all file names in the current directory.

files, err := ioutil.ReadDir(".")
if err != nil {
for _, f := range files {

Example output:


Visit all files and folders in a directory tree

Use the filepath.Walk function in package path/filepath.

The code in this example lists the paths and sizes of all files and directories in the file tree rooted at the current directory.

err := filepath.Walk(".",
    func(path string, info os.FileInfo, err error) error {
    if err != nil {
        return err
    fmt.Println(path, info.Size())
    return nil
if err != nil {

Example output:

. 1644
dev 1644
dev/null 0
dev/random 0
dev/urandom 0
dev/zero 0
etc 1644
etc/group 116
etc/hosts 20
etc/passwd 0
etc/resolv.conf 0
tmp 548
usr 822
usr/local 822
usr/local/go 822
usr/local/go/lib 822
usr/local/go/lib/time 822
usr/local/go/lib/time/ 366776

Share this page: