List all files (recursively) in a directory
yourbasic.org/golang
Directory listing
Use the ioutil.ReadDir
function in package io/ioutil
. It returns a sorted slice containing elements of type os.FileInfo
.
The code in this example prints a sorted list of all file names in the current directory.
files, err := ioutil.ReadDir(".")
if err != nil {
log.Fatal(err)
}
for _, f := range files {
fmt.Println(f.Name())
}
Example output:
dev
etc
tmp
usr
Visit all files and folders in a directory tree
Use the filepath.Walk
function in package path/filepath
.
- It walks a file tree calling a function of type
filepath.WalkFunc
for each file or directory in the tree, including the root. - The files are walked in lexical order.
- Symbolic links are not followed.
The code in this example lists the paths and sizes of all files and directories in the file tree rooted at the current directory.
err := filepath.Walk(".",
func(path string, info os.FileInfo, err error) error {
if err != nil {
return err
}
fmt.Println(path, info.Size())
return nil
})
if err != nil {
log.Println(err)
}
Example output:
. 1644
dev 1644
dev/null 0
dev/random 0
dev/urandom 0
dev/zero 0
etc 1644
etc/group 116
etc/hosts 20
etc/passwd 0
etc/resolv.conf 0
tmp 548
usr 822
usr/local 822
usr/local/go 822
usr/local/go/lib 822
usr/local/go/lib/time 822
usr/local/go/lib/time/zoneinfo.zip 366776