有没有办法只使用 Golang Glob 列出目录?
Is there no way to list directories only using Golang Glob?
Golang Glob 的行为与我预期的不同。假设我有一个具有以下结构的目录“foo”:
foo
|-- 1.txt
|-- 2.csv
|-- 3.json
|-- bar
`-- baz
我想做一个仅获取 foo 中的目录“bar”和“baz”的 glob。所以我试试这个:
path = "foo/*/"
matches, err := filepath.Glob(path)
if err != nil {
log.Fatal(err)
}
fmt.Println(matches)
这不会产生匹配项:
[]
如果我删除最后一个尾部斜杠并将路径更改为 "foo/*"
,我将同时获得文件和目录,这不是我想要的结果:
[foo/1.txt foo/2.csv foo/3.json foo/bar foo/baz]
我希望如果存在尾部斜杠,Glob 将 return 仅匹配 glob 模式的目录。我看到同样的问题是 noted on GitHub,但看不到任何解决方法 - 这听起来像是一个错误、一个记录不完整的功能,或者只是缺少预期的功能。
I've checked the Go docs for the Match function,Glob 使用的,它没有提到任何关于尾部斜杠的内容。
所以基本上:是否有解决方法,以便我可以使用 Glob 仅对特定路径下的目录进行 glob,或者我是否需要使用其他方法来完成此任务?
您可以遍历匹配项列表并对每个匹配项调用 os.Stat。 os.Stat returns 描述文件的 FileInfo 结构,它包含一个名为 IsDir 的方法,用于检查文件是否为目录。
示例代码:
// Note: Ignoring errors.
matches, _ := filepath.Glob("foo/*")
var dirs []string
for _, match := range matches {
f, _ := os.Stat(match)
if f.IsDir() {
dirs = append(dirs, match)
}
}
Golang Glob 的行为与我预期的不同。假设我有一个具有以下结构的目录“foo”:
foo
|-- 1.txt
|-- 2.csv
|-- 3.json
|-- bar
`-- baz
我想做一个仅获取 foo 中的目录“bar”和“baz”的 glob。所以我试试这个:
path = "foo/*/"
matches, err := filepath.Glob(path)
if err != nil {
log.Fatal(err)
}
fmt.Println(matches)
这不会产生匹配项:
[]
如果我删除最后一个尾部斜杠并将路径更改为 "foo/*"
,我将同时获得文件和目录,这不是我想要的结果:
[foo/1.txt foo/2.csv foo/3.json foo/bar foo/baz]
我希望如果存在尾部斜杠,Glob 将 return 仅匹配 glob 模式的目录。我看到同样的问题是 noted on GitHub,但看不到任何解决方法 - 这听起来像是一个错误、一个记录不完整的功能,或者只是缺少预期的功能。
I've checked the Go docs for the Match function,Glob 使用的,它没有提到任何关于尾部斜杠的内容。
所以基本上:是否有解决方法,以便我可以使用 Glob 仅对特定路径下的目录进行 glob,或者我是否需要使用其他方法来完成此任务?
您可以遍历匹配项列表并对每个匹配项调用 os.Stat。 os.Stat returns 描述文件的 FileInfo 结构,它包含一个名为 IsDir 的方法,用于检查文件是否为目录。 示例代码:
// Note: Ignoring errors.
matches, _ := filepath.Glob("foo/*")
var dirs []string
for _, match := range matches {
f, _ := os.Stat(match)
if f.IsDir() {
dirs = append(dirs, match)
}
}