List all files in a directory in Golang. Use filepath.Walk in Go standard
library, which is similar to Python os.walk.
import (
"fmt"
"os"
"path/filepath"
)
func WalkAllFilesInDir(dir string) error {
return filepath.Walk(dir, func(path string, info os.FileInfo, e error) error {
if e != nil {
return e
}
// check if it is a regular file (not dir)
if info.Mode().IsRegular() {
fmt.Println("file name:", info.Name())
fmt.Println("file path:", path)
}
return nil
})
}
If you do not want to walk into sub-directories, use ioutil.ReadDir.
Tested on: Ubuntu Linux 18.04, Go 1.10.2.
References: