在执行文件系统的WalkDir时,如何获取正在处理的路径?

huangapple go评论75阅读模式
英文:

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(&quot;.&quot;)
fs.WalkDir(fsys, &quot;.&quot;, func(p string, d fs.DirEntry, err error) error {
        fmt.Printf(&quot;%s  struct: %T  %v\n&quot;, 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  &amp;{../csvtsd csvtsd.go 0 &lt;nil&gt;}
csvtsd/csvtsd_test.go  struct: *os.unixDirent  &amp;{../csvtsd csvtsd_test.go 0 &lt;nil&gt;}
csvtsd/go.mod  struct: *os.unixDirent  &amp;{../csvtsd go.mod 0 &lt;nil&gt;}

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(&quot;.&quot;)
fs.WalkDir(fsys, &quot;.&quot;, func(p string, d fs.DirEntry, err error) error {
     fmt.Printf(&quot;dir=%s, path=%s\n&quot;, path.Dir(p), p)
     return nil
})

huangapple
  • 本文由 发表于 2023年1月15日 07:37:35
  • 转载请务必保留本文链接:https://go.coder-hub.com/75121996.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定