Golang: path/filepath.Walk

By Xah Lee. Date: . Last updated: .

filepath.Walk

here's a example of using filepath.Walk from package "path/filepath"

to go thru all files and directory, use

filepath.Walk(dirPath, doF) walks dirPath, for each file or dir, it calls doF

doF is a function you need to define. It do something for each file.

💡 TIP: filepath.Walk is old. For better way, see Golang: Walk Directory, List Files

Argument Passed to the Process File Function

filepath.Walk(dirPath, doF) passes 3 arguments to doF.

The spec for doF is this:

var doF = func(xpath string, xinfo os.FileInfo, xerr error) error {body}

The arguments passed to the doF are:

xpath

the full path of current file or directory.

xinfo

A os.FileInfo object. It contain info about the file.

e.g. use it like these:

xinfo.IsDir()

arg2.Size()

xerr (type error)

If there's a error.

FileInfo

A FileInfo is a interface that has methods of a file.

type FileInfo interface {
    Name() string       // base name of the file
    Size() int64        // length in bytes for regular files; system-dependent for others
    Mode() FileMode     // file mode bits
    ModTime() time.Time // modification time
    IsDir() bool        // abbreviation for Mode().IsDir()
    Sys() interface{}   // underlying data source (can return nil)
}

Error

The error built-in interface type is the conventional interface for representing an error condition, with the nil value representing no error.

type error interface {
    Error() string
}

Return Value of Process File Function

When there's a problem, a error is passed to doF. The function doF can do whatever with it.

doF must return one of:

nil

Normal.

filepath.SkipDir

If doF returns filepath.SkipDir, then filepath.Walk will skip it. Meaning: If current path is dir, skip it, but if current path is a file, then skip rest of files in the directory.

value of type error

If doF returns a error, then filepath.Walk returns a error. The walk is stopped

(error is a interface)

Example

package main

import (
	"fmt"
	"os"
	"path/filepath"
)

var xDir = "/Users/xah/web/xahlee_info/golang/"

// go thru a dir and print all file name and extension

func main() {

	var doF = func(xpath string, xinfo os.FileInfo, xerr error) error {

		// first thing to do, check error. and decide what to do about it
		if xerr != nil {
			fmt.Printf("error [%v] at a path [%q]\n", xerr, xpath)
			return xerr
		}

		fmt.Printf("xpath: %v\n", xpath)

		// find out if it's a dir or file, if file, print info
		if xinfo.IsDir() {
			fmt.Printf("is dir.\n")
		} else {
			fmt.Printf("  dir: [%v]\n", filepath.Dir(xpath))
			fmt.Printf("  file name [%v]\n", xinfo.Name())
			fmt.Printf("  extenion: [%v]\n", filepath.Ext(xpath))
		}

		return nil
	}

	err := filepath.Walk(xDir, doF)

	if err != nil {
		fmt.Printf("error walking the path %q: %v\n", xDir, err)
	}
}