I Spy Code - GO

File tree traversal

Question:

How to how to walk a directory with golang?

Answer:

The function filepath.Walk() walks the file tree rooted at root, calling walkFn for each file or directory in the tree, including root.

Here is a golang example that shows how to list all of the files recursively in a directory:

Source: (example.go)

package main
 
import (
   "fmt"
   "os"
   "path/filepath"
)
 
func walkfunc(path string, info os.FileInfo, err error) error {
   fmt.Println("Path:", path)
   return nil
}
 
func main() {
   filepath.Walk("/tmp/mydir", walkfunc)
}
 

Output:

$ go run example.go
Path: /tmp/mydir
Path: /tmp/mydir/file1
Path: /tmp/mydir/file2
Path: /tmp/mydir/file3
Path: /tmp/mydir/subdir1
Path: /tmp/mydir/subdir1/file4
Path: /tmp/mydir/subdir1/file5
Path: /tmp/mydir/subdir2
Path: /tmp/mydir/subdir2/file6
Path: /tmp/mydir/subdir2/file7

$ ls -R1 /tmp/mydir/
file1
file2
file3
subdir1
subdir2

/tmp/mydir//subdir1:
file4
file5

/tmp/mydir//subdir2:
file6
file7

References:

https://golang.org/pkg/path/filepath/#Walk

Questions answered by this page:

How to list all the files in a directory and subdirectories in golang?
How to walk a file system in go lang?
How to list all the files recursively in a directory using golang?