golang--遍历文件夹读取所有文件数据

只读取当前指定路径下的文件,跳过文件夹

func FileForEach(fileFullPath string) []fs.FileInfo {
	files, err := ioutil.ReadDir(fileFullPath)
	if err != nil {
		log.Fatal(err)
	}
	var myFile []fs.FileInfo
	for _, file := range files {
		fmt.Println(file.Name())
		if file.IsDir() {
			continue
		}
		myFile = append(myFile,file)
	}
	return myFile
}

读取指定路径下的所有文件,包括子文件夹下的

func FileForEachComplete(fileFullPath string) []fs.FileInfo {
	files, err := ioutil.ReadDir(fileFullPath)
	if err != nil {
		log.Fatal(err)
	}
	var myFile []fs.FileInfo
	for _, file := range files {
		if file.IsDir() {
			path := strings.TrimSuffix(fileFullPath, "/") + "/" + file.Name()
			subFile := FileForEachComplete(path)
			if len(subFile) > 0 {
				myFile = append(myFile, subFile...)
			}
		} else {
			myFile = append(myFile, file)
		}
	}
	return myFile
}

你可能感兴趣的:(Golang,golang)