如何在 Golang 的 filepath.walk() func 中设置目录递归迭代的深度?
How to set depth for recursive iteration of directories in filepath.walk() func in Golang?
我想在一个包含各种子目录的目录中搜索特定类型的文件。为此,我在 Golang 中使用 filepath.walk()
。但是,我不想递归迭代超出我知道该文件不存在的最大深度。
Golang 中是否有这样的预置function/library?
首先,你应该使用Go 1.16引入的filepath.WalkDir
,它比filepath.Walk
更有效率。
Walk is less efficient than WalkDir, introduced in Go 1.16, which avoids calling os.Lstat on every visited file or directory.
那么,没有办法将最大深度指定为直接参数。您必须在 WalkDirFunc
.
中计算递归深度
显然计算文件路径中的分隔符是一个 acceptable strategy(并且可以说比其他可能的技巧更简单),因此解决方案可能如下所示:
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
})
所以目录结构如下:
.
└── root
├── a.txt
├── b.txt
└── root1
├── a.txt
└── root2
├── a.txt
├── b.txt
├── root3
│ └── a.txt
└── root4
并假设 root
位于深度 0
,上面的代码打印出:
skip root/root1/root2/root3
skip root/root1/root2/root4
我想在一个包含各种子目录的目录中搜索特定类型的文件。为此,我在 Golang 中使用 filepath.walk()
。但是,我不想递归迭代超出我知道该文件不存在的最大深度。
Golang 中是否有这样的预置function/library?
首先,你应该使用Go 1.16引入的filepath.WalkDir
,它比filepath.Walk
更有效率。
Walk is less efficient than WalkDir, introduced in Go 1.16, which avoids calling os.Lstat on every visited file or directory.
那么,没有办法将最大深度指定为直接参数。您必须在 WalkDirFunc
.
显然计算文件路径中的分隔符是一个 acceptable strategy(并且可以说比其他可能的技巧更简单),因此解决方案可能如下所示:
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
})
所以目录结构如下:
.
└── root
├── a.txt
├── b.txt
└── root1
├── a.txt
└── root2
├── a.txt
├── b.txt
├── root3
│ └── a.txt
└── root4
并假设 root
位于深度 0
,上面的代码打印出:
skip root/root1/root2/root3
skip root/root1/root2/root4