在Go语言中,可以使用osfilepath包来统计目录下有多少个文件夹。

下面是一个示例代码:

package main

import (
	"fmt"
	"os"
	"path/filepath"
)

func countDirectories(path string) (int, error) {
	count := 0

	err := filepath.Walk(path, func(path string, info os.FileInfo, err error) error {
		if err != nil {
			return err
		}

		if info.IsDir() {
			count++
		}

		return nil
	})

	if err != nil {
		return 0, err
	}

	return count, nil
}

func main() {
	path := "/path/to/directory"

	count, err := countDirectories(path)
	if err != nil {
		fmt.Println("Error:", err)
		return
	}

	fmt.Println("Number of directories:", count)
}

在上面的示例中,countDirectories函数使用filepath.Walk函数来遍历指定目录及其子目录中的所有文件和文件夹。在每次遍历时,判断当前遍历到的路径是否是文件夹,如果是则计数器加一。最后返回计数器的值。

然后在main函数中,调用countDirectories函数来统计指定目录下的文件夹数量,并输出结果。

需要注意的是,需要将path变量替换为你要统计的目录的实际路径。

golang统计目录下面有多少个文件夹

原文地址: https://www.cveoy.top/t/topic/hPX8 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录