如何递归遍历文件和目录



当试图运行程序是需要显示所有。md文件,我有一个测试子文件夹与。md在它,但脚本没有找到它?


import (
"fmt"
"log"
"strings"
"os"
)
func main() {
dir, err := os.ReadDir(".")
if err != nil {
log.Fatal(err)
}
for _, x := range dir {
if strings.HasSuffix(x.Name(), ".md") {
fmt.Println(x.Name())
}
}
}

您可以使用Walkdir:

package main
import (
"io/fs"
"path/filepath"
)

func main() {
filepath.WalkDir(".", func(s string, d fs.DirEntry, e error) error {
if e != nil { return e }
if ! d.IsDir() {
println(s)
}
return nil
})
}

您需要使用filepath。WalkDir来递归地检查目录,或者您可以使用1.16中引入的filepath.Walk。os.ReadDir只在指定的目录下工作。

filepath.Walk(".", func(path string, info fs.FileInfo, err error) error {
if err != nil {
fmt.Printf("prevent panic by handling failure accessing a path %q: %vn", path, err)
return err
}
if strings.HasSuffix(info.Name(), ".md") {
fmt.Printf("visited file or dir: %qn", path)
}
return nil
})

为了增加已经足够的响应,这里是我使用container/ring结构的实现

完整代码在这里


type (
DirectoryGraph struct {
RootPath string
root     *ring.Ring
Node     *ring.Ring
}
)
func NewDirectoryGraph(root string) DirectoryGraph {
r := ring.New(1)
graph := DirectoryGraph{
RootPath: root,
root:     r,
Node:     r,
}
filepath.WalkDir(graph.RootPath, graph.walk)
return graph
}
func (g DirectoryGraph) walk(s string, d fs.DirEntry, e error) error {
if e != nil {
return e
}
next := ring.New(1)
node := g.serialize(s, d, e)
next.Value = node
g.root.Link(next).Next()
return nil
}
// Serializes a file-node
func (g DirectoryGraph) serialize(s string, d fs.DirEntry, e error) FileNode {
n := FileNode{
Path: s,
Dir:  d,
Sys:  SysInfo{},
}
...
return n
}

最新更新