英文:
when doing a WalkDir of a FileSystem, how do you get access to the path that you are working on
问题
我正在使用相对较新的FileSystem样式来进行常规的目录遍历,以通常的递归方式处理每个文件。尽管我可以在输出中看到它,但我无法弄清楚如何获取目录数据(直到最后一个/的路径)。我缺少正确的getter名称,或者可能是一个类型转换/断言。
关键代码如下:
fsys := os.DirFS(".")
fs.WalkDir(fsys, ".", func(p string, d fs.DirEntry, err error) error {
fmt.Printf("%s struct: %T %v\n", p, d, d)
它打印出当前文件名和扩展名,fs.DirEntry的类型,以及fsDirEntry结构。
类似于这样:
csvtsd/csvtsd.go struct: *os.unixDirent &{../csvtsd csvtsd.go 0 <nil>}
csvtsd/csvtsd_test.go struct: *os.unixDirent &{../csvtsd csvtsd_test.go 0 <nil>}
csvtsd/go.mod struct: *os.unixDirent &{../csvtsd go.mod 0 <nil>}
你可以看到,"p"通常是路径和文件名:csvtsd/csvtsd.go,类型是*os.unixDirent,Dirent中有四个字段,即路径(直到最后一个/),文件名和扩展名,以及其他两个字段。
英文:
I'm using the reasonably new FileSystem style to do the usual directory walk
processing every file in the usual recursive manner.
I can't figure out how to get the directory data (the path up to the last /)
even though I can see it in the output.
I am missing the proper name of the getter, or perhaps a cast/type assertion
Playground:
https://go.dev/play/p/Fde-rAA5YZI
The key code is
fsys := os.DirFS(".")
fs.WalkDir(fsys, ".", func(p string, d fs.DirEntry, err error) error {
fmt.Printf("%s struct: %T %v\n", p, d, d)
which prints "'p" the current file name and extension
the type of the fs.DirEntry and then the fsDirEntry structure
Something like this:
csvtsd/csvtsd.go struct: *os.unixDirent &{../csvtsd csvtsd.go 0 <nil>}
csvtsd/csvtsd_test.go struct: *os.unixDirent &{../csvtsd csvtsd_test.go 0 <nil>}
csvtsd/go.mod struct: *os.unixDirent &{../csvtsd go.mod 0 <nil>}
You can see that the "p" is typically the path and filename: csvtsd/csvtsd.go
the type is a *os.unixDirent
and there are four fields in the Dirent, the path (up to the last /)
the filename and extension, and two other fields.
答案1
得分: 1
从DirEntry中获取目录名的方法。
使用path.Dir从路径参数中获取目录,然后传递给walk函数:
fsys := os.DirFS(".")
fs.WalkDir(fsys, ".", func(p string, d fs.DirEntry, err error) error {
fmt.Printf("dir=%s, path=%s\n", path.Dir(p), p)
return nil
})
英文:
There is not method to get the directory name from the DirEntry
Use path.Dir to get the directory from the path argument to the walk function:
fsys := os.DirFS(".")
fs.WalkDir(fsys, ".", func(p string, d fs.DirEntry, err error) error {
fmt.Printf("dir=%s, path=%s\n", path.Dir(p), p)
return nil
})
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论