The GO language implements methods for listing directories and traversing them

  • 2020-05-09 18:43:55
  • OfStack

This article illustrates how the GO language implements listing and traversing directories. Share with you for your reference. The details are as follows:

The GO language gets the directory list with ioutil.ReadDir (), and traverses the directory with filepath.Walk ().

The specific sample code is as follows:

package main
import (
 "fmt"
 "io/ioutil"
 "os"
 "path/filepath"
 "strings"
) // Gets all files in the specified directory, do not enter 1 Level directory search, can match suffix filtering.
func ListDir(dirPth string, suffix string) (files []string, err error) {
 files = make([]string, 0, 10)  dir, err := ioutil.ReadDir(dirPth)
 if err != nil {
  return nil, err
 }  PthSep := string(os.PathSeparator)
 suffix = strings.ToUpper(suffix) // Ignore the case of suffix matching  for _, fi := range dir {
  if fi.IsDir() { // Ignore the directory
   continue
  }
  if strings.HasSuffix(strings.ToUpper(fi.Name()), suffix) { // Match the file
   files = append(files, dirPth+PthSep+fi.Name())
  }
 }  return files, nil
} // Gets all files in the specified directory and all subdirectories to match the suffix filter.
func WalkDir(dirPth, suffix string) (files []string, err error) {
 files = make([]string, 0, 30)
 suffix = strings.ToUpper(suffix) // Ignore the case of suffix matching  err = filepath.Walk(dirPth, func(filename string, fi os.FileInfo, err error) error { // Directory traversal
  //if err != nil { // Ignore the error
  // return err
  //}   if fi.IsDir() { // Ignore the directory
   return nil
  }   if strings.HasSuffix(strings.ToUpper(fi.Name()), suffix) {
   files = append(files, filename)
  }   return nil
 })  return files, err
} func main() {
 files, err := ListDir("D:\\Go", ".txt")
 fmt.Println(files, err)  files, err = WalkDir("E:\\Study", ".pdf")
 fmt.Println(files, err)
}

I hope this article has been helpful to you in the programming of GO language.


Related articles: