This is a creation in Article, where the information may have evolved or changed.
Package Main
Import (
"FMT"
"Io/ioutil"
"OS"
"Path/filepath"
"Strings"
)
Gets all the files under the specified directory, does not go to the next level of directory search, can 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 files under the specified directory and all subdirectories, and can match suffix filtering.
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)
}