转:GoLang 遍历目录的不同方法


GoLang 遍历目录,一个常用的功能。

package main
import (
    "path/filepath"
    "os"
    "fmt"
    "flag"
)

func getFilelist(path string) {
    err := filepath.Walk(path, func(path string, f os.FileInfo, err error) error {
        if ( f == nil ) {return err}
        if f.IsDir() {return nil}
        println(path)
        return nil
    })
    if err != nil {
        fmt.Printf("filepath.Walk() returned %v\n", err)
    }
}

func main(){
    flag.Parse()
    root := flag.Arg(0)
    getFilelist(root)
}

 

下面这个只列出当前文件夹下的文件:

package main

import "io/ioutil"

func listAll(path string) {
    files, _ := ioutil.ReadDir(path)
    for _, fi := range files {
        if fi.IsDir() {
            //listAll(path + "/" + fi.Name())
            println(path + "/" + fi.Name())
        } else {
            println(path + "/" + fi.Name())
        }
    }
}
func main() {
    listAll(".")
}

另一个版本:

package main

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

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
    fmt.Println(root)
    filepath.Walk("./", walkpath)
}

 

 

版本 4:

package main

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

func main() ([]string, error) {
    searchDir := "c:/path/to/dir"

    fileList := []string{}
    err := filepath.Walk(searchDir, func(path string, f os.FileInfo, err error) error {
        fileList = append(fileList, path)
        return nil
    })

    for _, file := range fileList {
        fmt.Println(file)
    }
}

 

ps:https://www.golangnote.com/topic/86.html

Archives