我想在D:\中列出所有的txt文件
func main() {
var files []string
filepath.WalkDir("D:\\", func(path string, entry fs.DirEntry, err error) error {
if err != nil {
return err
}
ok := strings.HasSuffix(path, ".txt")
if ok {
files = append(files, path)
}
return nil
})
for _, v := range files {
fmt.Println(v)
}
}
但是它并没有把它们列在所有的目录中。
结果:
D:\$RECYCLE.BIN\S-1-5-21-1494130436-1676888839-3129388282-1001\$I1KMI26.txt
D:\GoLand 2022.2.3\build.txt
发布于 2022-10-13 20:15:56
您可以使用以下代码:
// ListFiles is delegated to find the files from the given directory, recursively for each dir
func ListFiles(path string) ([]string, error) {
var fileList []string
// Read all the file recursively
if _, err := os.Stat(path); os.IsNotExist(err) {
return nil, err
}
err := filepath.Walk(path, func(file string, f os.FileInfo, err error) error {
if IsFile(file) {
fileList = append(fileList, file)
}
return nil
})
if err != nil {
return nil, err
}
return fileList, nil
}
参考资料:
https://stackoverflow.com/questions/74042010
复制相似问题