Go: 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 {
        log.Println(err)
}

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/zoneinfo.zip 366776

Comments

Be the first to comment!