How to iterate over folders in Golang?
In Go language, the filepath package can be used to traverse folders. Here is a simple example:
package main
import (
"fmt"
"os"
"path/filepath"
)
func main() {
// 设置要遍历的文件夹路径
root := "/path/to/folder"
err := filepath.Walk(root, func(path string, info os.FileInfo, err error) error {
if err != nil {
return err
}
// 判断是否是文件夹
if info.IsDir() {
fmt.Println("文件夹:", path)
} else {
fmt.Println("文件:", path)
}
return nil
})
if err != nil {
fmt.Println("遍历文件夹时发生错误:", err)
}
}
In the above example, we utilize the filepath.Walk function to traverse through folders. This function takes a folder path as a parameter and recursively traverses through the folder and its subfolders. In the callback function for each folder and file, we can access the file path, information (such as if it is a folder), and any possible errors.
You just need to replace “/path/to/folder” with the path of the folder you want to traverse.