自动化管理文件和文件夹

遍历文件夹


遍历文件夹及子文件夹

path/filepathfunc Walk(root string, walkFn WalkFunc) errorWalkrootwalkFnroot/walkFnWalk
path/filepathtype WalkFunc func(path string, info os.FileInfo, err error) errorWalk/WalkFuncWalkrootWalkrootdiradir/awalkFnwalkFninfopath/os.FileInfo
patherrWalkFuncWalkWalkWalkwalkFnSkipDirWalk

示例:

package mainimport ("fmt""os""path/filepath")func walkFunc(path string, info os.FileInfo, err error) error {fmt.Printf("%s\n", path)return nil}func main() {//遍历打印所有的文件名filepath.Walk(`F:\blog`, walkFunc)}

普通遍历文件夹

示例:

package mainimport ("fmt""os")func main() {f, err := os.Open(`F:\blog\officeauto`)if err != nil {panic(err)}fs, err := f.Readdir(0)if err != nil {panic(err)}for _, f := range fs {fmt.Println(f.Name())}}

示例:

package mainimport ("fmt""io/ioutil")func main() {fs, err := ioutil.ReadDir(`F:\blog\officeauto`)if err != nil {panic(err)}for _, f := range fs {fmt.Println(f.Name())}}

递归遍历文件夹

示例:

package mainimport ("fmt""io/ioutil")func WalkDir(filepath string, level int) ([]string, error) {prefix :&#61; "|"for i :&#61; 0; i < level; i&#43;&#43; {prefix &#43;&#61; "------"}// files为当前目录下的所有文件名称【包括文件夹】files, err :&#61; ioutil.ReadDir(filepath)if err !&#61; nil {return nil, err}var allfile []stringfor _, v :&#61; range files {// 全路径 &#43; 文件名称fullPath :&#61; filepath &#43; "\\" &#43; v.Name()// 如果是目录if v.IsDir() {allfile &#61; append(allfile, prefix &#43; v.Name())// 遍历改路径下的所有文件a, _ :&#61; WalkDir(fullPath, level &#43; 1)allfile &#61; append(allfile, a...)} else {// 如果不是文件夹&#xff0c;就直接追加到路径下allfile &#61; append(allfile, prefix &#43; v.Name())}}return allfile, nil}func main() {files, _ :&#61; WalkDir(&#96;F:\blog&#96;, 1)for _, v :&#61; range files {fmt.Println(v)}}