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
+17k Golang : When to use init() function?
+6.7k Golang : How to setup a disk space used monitoring service with Telegram bot
+12.2k Golang : Search and extract certain XML data example
+13.9k Golang : Fix image: unknown format error
+8.1k Golang : Oanda bot with Telegram and RSI example
+14.2k Golang : Send email with attachment(RFC2822) using Gmail API example
+9.3k Golang : How to extract video or image files from html source code
+19k Golang : Delete item from slice based on index/key position
+8.6k Golang : Gaussian blur on image and camera video feed examples
+5.1k Golang : Get FX sentiment from website example
+5.5k Get website traffic ranking with Similar Web or Alexa
+15k nginx: [emerg] unknown directive "ssl"