GolangNote

Golang笔记

GoLang 遍历目录的不同方法

Permalink

GoLang 遍历目录,一个常用的功能。下面介绍 4 种常用的遍历目录的方法。

Go: filepath 遍历目录
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
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)
}

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

Go: ioutil 列出当前文件夹下的文件
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
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(".")
}

另一个版本:

Go: 目录遍历
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
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:

Go: 目录遍历
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
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)
    }
}

本文网址: https://golangnote.com/topic/86.html 转摘请注明来源

Related articles

Write a Comment to "GoLang 遍历目录的不同方法"

Submit Comment Login
Based on Golang + fastHTTP + sdb | go1.20 Processed in 0ms