每日一题 【每日一题】实现文件查询功能 -Python-20210907

Jack · 2021年09月07日 · 最后由 lework 回复于 2021年12月25日 · 58 次阅读
本帖已被设为精华帖!

实现遍历目录与子目录,抓取.txt 文件

Jack 将本帖设为了精华贴 09月07日 21:45

参考代码:

from glob import iglob

def func(fp, postfix):
    for i in iglob(f"{fp}/**/*{postfix}", recursive=True):
        print(i)

if __name__ == "__main__":
    postfix = ".txt"
    func("F:\\", postfix)
package main

import (
    "fmt"
    "io/ioutil"
    "os"
    "strings"
)

var fileList []string

func getExtFile(path string, ext string ) ([]string, error) {
    rd, err := ioutil.ReadDir(path)

    if err !=nil {
        fmt.Println("read dir fail: ", err)
        return fileList, err
    }

    for _, file := range rd {
        filePath := path + string(os.PathSeparator) + file.Name()
        if file.IsDir() {
            _, _ = getExtFile(filePath, ext)
        } else {
            if ok:= strings.HasSuffix(filePath, ext); ok {
                fileList = append(fileList, filePath)
            }

        }
    }

    return fileList,err
}

func main() {
    /*
    实现遍历目录与子目录,抓取.txt 文件
    */

    f,_ := getExtFile("d://tmp/", ".yaml")

    for _,val := range f {
        fmt.Println(val)
    }

}
需要 登录 后方可回复, 如果你还没有账号请点击这里 注册