如何在Golang中的filepath.walk()函数中设置目录递归迭代的深度?

inf*_*nk- 4 go filepath

我想在包含各种子目录的目录中搜索特定类型的文件。我filepath.walk()在 Golang 中使用这个。但是,我不想递归迭代超出我知道该文件不能存在的最大深度。

Golang 中有这样的预建函数/库吗?

bla*_*een 6

首先,你应该使用filepath.WalkDirGo 1.16中的introduced,它比filepath.Walk.

\n
\n

Walk 的效率低于 Go 1.16 中引入的 WalkDir,它避免了对每个访问的文件或目录调用 os.Lstat。

\n
\n

然后,无法将最大深度指定为直接参数。您必须计算WalkDirFunc.

\n

显然,计算文件路径中的分隔符是一种可接受的策略(并且可以说比其他可能的技巧更简单),因此解决方案可能如下所示:

\n
    maxDepth := 2\n    rootDir := "root"\n    err := filepath.WalkDir(rootDir, func(path string, d fs.DirEntry, err error) error {\n        if err != nil {\n            // handle possible path err, just in case...\n            return err\n        }\n        if d.IsDir() && strings.Count(path, string(os.PathSeparator)) > maxDepth {\n            fmt.Println("skip", path)\n            return fs.SkipDir\n        }\n        // ... process entry\n        return nil\n    })\n
Run Code Online (Sandbox Code Playgroud)\n

因此 dir 结构如下:

\n
.\n\xe2\x94\x94\xe2\x94\x80\xe2\x94\x80 root\n    \xe2\x94\x9c\xe2\x94\x80\xe2\x94\x80 a.txt\n    \xe2\x94\x9c\xe2\x94\x80\xe2\x94\x80 b.txt\n    \xe2\x94\x94\xe2\x94\x80\xe2\x94\x80 root1\n        \xe2\x94\x9c\xe2\x94\x80\xe2\x94\x80 a.txt\n        \xe2\x94\x94\xe2\x94\x80\xe2\x94\x80 root2\n            \xe2\x94\x9c\xe2\x94\x80\xe2\x94\x80 a.txt\n            \xe2\x94\x9c\xe2\x94\x80\xe2\x94\x80 b.txt\n            \xe2\x94\x9c\xe2\x94\x80\xe2\x94\x80 root3\n            \xe2\x94\x82\xc2\xa0\xc2\xa0 \xe2\x94\x94\xe2\x94\x80\xe2\x94\x80 a.txt\n            \xe2\x94\x94\xe2\x94\x80\xe2\x94\x80 root4\n
Run Code Online (Sandbox Code Playgroud)\n

假设root位于深度0,上面的代码打印:

\n
skip root/root1/root2/root3\nskip root/root1/root2/root4\n
Run Code Online (Sandbox Code Playgroud)\n