The examples in this article describe how the go implementation lists directories and traverses directories. Share to everyone for your reference. Specifically as follows:
The Go language gets a list of directories with Ioutil. ReadDir (), traverse directory with filepath. Walk (), use the method lesson to refer to this example.
The specific example code is as follows:
Copy Code code as follows:
Package Main
Import (
"FMT"
"Io/ioutil"
"OS"
"Path/filepath"
"Strings"
)
Gets all the files in the specified directory and does not go to the next level of directory search to match the suffix filter.
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 suffix matching case
For _, Fi: = Range dir {
If Fi. Isdir () {//Ignore directory
Continue
}
If strings. Hassuffix (Strings. ToUpper (FI. Name ()), suffix) {//matching file
Files = append (files, Dirpth+pthsep+fi. Name ())
}
}
return files, nil
}
Gets all the files in the specified directory and all subdirectories, and can match the suffix filter.
Func walkdir (dirpth, suffix string) (files []string, err Error) {
Files = Make ([]string, 0, 30)
suffix = strings. ToUpper (suffix)//ignore suffix matching case
Err = filepath. Walk (Dirpth, func (filename string, fi os.) FileInfo, err Error) error {//traverse directory
If Err!= nil {//Ignore error
return err
//}
If Fi. Isdir () {//Ignore 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 will help you with your go language program.