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

Golang 泛型性能初识

编程时,我们通常需要编写“泛型”函数,其中确切的数据类型并不重要。例如,您可能想编写一个简单的函数来对数字进行求和。Go 直到最近才有这个概念,但最近才添加了它(从1.18版开始)。...

Golang 单实例实现网站多域名请求

有时候写网站,为了统一的后端,把不同业务都集中到一个后端,这时就需要处理多域名的请求,在 Go http server 里实现很简单,只需把不同域名映射到不同的 `http.Handler`。...

Golang phantomjs 动态代理实现

phantomjs 是个很优秀的软件,虽然现在被chrome headless 抢了风头,但在某些特定场合,使用phantomjs 还是很方便,这里是介绍使用Go 实现动态代理。...

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

Submit Comment Login
Based on Golang + fastHTTP + sdb | go1.22.3 Processed in 1ms