亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何在 Golang 中的 filepath.walk() func 中為目錄的遞歸迭代設置深度?

如何在 Golang 中的 filepath.walk() func 中為目錄的遞歸迭代設置深度?

Go
ibeautiful 2022-11-08 16:24:13
我想在包含各種子目錄的目錄中搜索特定類型的文件。我filepath.walk()在 Golang 中為此使用。但是,我不想遞歸迭代超出我知道該文件不存在的最大深度。Golang 中有沒有這樣的預建函數/庫?
查看完整描述

2 回答

?
Qyouu

TA貢獻1786條經驗 獲得超11個贊

首先,你應該使用filepath.WalkDirGo 1.16 中引入的,它比filepath.Walk.

Walk 的效率低于 Go 1.16 中引入的 WalkDir,后者避免在每個訪問的文件或目錄上調用 os.Lstat。

然后,無法將最大深度指定為直接參數。您必須計算WalkDirFunc.

顯然,在文件路徑中計算分隔符是一種可接受的策略(并且可以說比其他可能的技巧更簡單),因此解決方案可能如下所示:

    maxDepth := 2

    rootDir := "root"

    err := filepath.WalkDir(rootDir, func(path string, d fs.DirEntry, err error) error {

        if err != nil {

            // handle possible path err, just in case...

            return err

        }

        if d.IsDir() && strings.Count(path, string(os.PathSeparator)) > maxDepth {

            fmt.Println("skip", path)

            return fs.SkipDir

        }

        // ... process entry

        return nil

    })

所以dir結構如下:


.

└── root

    ├── a.txt

    ├── b.txt

    └── root1

        ├── a.txt

        └── root2

            ├── a.txt

            ├── b.txt

            ├── root3

            │   └── a.txt

            └── root4

并假設root在 depth 0,上面的代碼打印上面的代碼:


skip root/root1/root2/root3

skip root/root1/root2/root4


查看完整回答
反對 回復 2022-11-08
?
神不在的星期二

TA貢獻1963條經驗 獲得超6個贊

func ControlDeepWalk(basepath string, count int, hard, debug bool) error {

    var (

        stock       = make(map[string][]string)

        countBase   = 0

        correctdirs []string

    )

    base := filepath.Base(basepath)

    dirbase := filepath.Dir(basepath)

    countBase = len(strings.Split(filepath.Dir(basepath), "/"))

    if debug {

        log.Printf("countbase: %v  %v\n", strings.Split(filepath.Dir(basepath), "/"), countBase)

        log.Printf("base :%v : %v : %v\n", base, dirbase, strings.Split(basepath, "/"))

    }


    err := filepath.WalkDir(basepath, func(path string, d fs.DirEntry, err error) error {

        if err != nil {

            if debug {

                log.Printf("--error inf walkdir function, exit")

            }

            return err

        }

        if d.IsDir() {

            if filepath.Dir(path) == filepath.Dir(basepath) {

                if debug {

                    log.Printf("found root directory, skipping  %v :  %v\n", filepath.Dir(path), filepath.Dir(basepath))

                }

            } else {

                compare := false

                if hard {

                    compare = len(strings.Split(filepath.Dir(path), "/")) == countBase+count

                } else {

                    compare = len(strings.Split(filepath.Dir(path), "/")) <= countBase+count

                }

                if compare {

                    if debug {

                        log.Printf("-found dir: [%v] %v\n", path, d.Name())

                    }

                    stock[filepath.Dir(filepath.Join(path, d.Name()))] = []string{}

                    correctdirs = append(correctdirs, filepath.Dir(filepath.Join(path, d.Name())))

                }

            }

        } else {

            fdir, ffile := filepath.Split(path)

            for _, x := range correctdirs {

                if x == filepath.Dir(fdir) {

                    if debug {

                        log.Printf("-found file:%v  : %v   %v  %v \n", d.Name(), path, fdir, ffile)

                    }

                    stock[x] = append(stock[x], d.Name())

                }

            }

        }

        return nil

    })

    if debug {

        for k, v := range stock {

            log.Printf("%v : %v \n", k, v)

        }

        log.Printf("%v\n", stock)

    }

    return err

}




func main() {

    p := "/backup/backuper/test"

    count := 2

    _ = ControlDeepWalk(p, count, false, true)


}


查看完整回答
反對 回復 2022-11-08
  • 2 回答
  • 0 關注
  • 324 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號