如何在 Go 中获取特定扩展名的文件数量?

Vol*_*il3 2 go

我用于ioutil迭代文件夹:

existingFiles, err := ioutil.ReadDir(indexPath)
Run Code Online (Sandbox Code Playgroud)

我想获取文件的数量(如果它们属于 类型).txt。我怎样才能做到这一点而不循环?有什么办法可以通过模式吗?

ber*_*eal 5

您可以使用filepath.Glob()

pattern := filepath.Join(indexPath, "*.txt")
files, err := filepath.Glob(pattern)
if err == nil {
    fmt.Printf("Found %d files.\n", len(files))
}
Run Code Online (Sandbox Code Playgroud)