Golang : Read directory content with filepath.Walk()
Golang's filepath.Walk function allow a program to traverse a directory content and tree with ease. In this tutorial, we will see how to read a directory and display its content name with file size. This example will use the http://golang.org/pkg/path/filepath/#Walk function.
readdirwalk.go
package main
import (
"path/filepath"
"os"
"flag"
"fmt"
)
func walkpath(path string, f os.FileInfo, err error) error {
fmt.Printf("%s with %d bytes\n", path,f.Size())
return nil
}
func main() {
flag.Parse()
root := flag.Arg(0) // 1st argument is the directory location
filepath.Walk(root, walkpath)
}
execute go run readdirwalk.go ./
and see how it goes. You can change to different directory and test out the output as well. Hope this tutorial is helpful to you.
See also : Golang : Read directory content with os.Open
By Adam Ng
IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.
Advertisement
Tutorials
+7.1k Golang : Quadratic example
+38.6k Golang : Read tab delimited file with encoding/csv package
+7.7k Golang : flag provided but not defined error
+38.7k Golang : Marshal and unmarshal json.RawMessage struct example
+11.1k Android Studio : Use image as AlertDialog title with custom layout example
+26.1k Golang : missing Git command
+10.7k Golang : convert rune to unicode hexadecimal value and back to rune character
+6.6k Golang : Simple histogram example
+4.5k Golang : Skip or discard items of non-interest when iterating example
+47.6k Golang : Unmarshal JSON from http response
+7k Golang : How to control fmt or log print format?
+7.7k Golang : Sort and reverse sort a slice of floats