go语言列出文件夹下文件夹
In this article I explain how to get a list of files inside a folder on the filesystem, a task also called tree traversing, with Go.
在本文中,我解释了如何使用Go获取文件系统上的文件夹内的文件列表,该任务也称为树遍历 。
There are two handy stdlib functions that you can use depending on your goal.
您可以根据自己的目标使用两个方便的stdlib函数。
I list 3 ways: using filepath.Walk
, ioutil.ReadDir
or os.File.Readdir
.
我列出了3种方法:使用filepath.Walk
, ioutil.ReadDir
或os.File.Readdir
。
使用filepath.Walk
(Using filepath.Walk
)
The path/filepath
stdlib package provides the handy Walk function. It automatically scans subdirectories, though, so make sure this is what you actually want.
path/filepath
stdlib软件包提供了便捷的Walk功能。 但是,它会自动扫描子目录,因此请确保这是您真正想要的。
Usage is very simple:
用法很简单:
package main
import (
"fmt"
"os"
"path/filepath"
)
func main() {
var files []string
root := "/some/folder/to/scan"
err := filepath.Walk(root, func(path string, info os.FileInfo, err error) error {
files = append(files, path)
return nil
})
if err != nil {
panic(err)
}
for _, file := range files {
fmt.Println(file)
}
}