遍历目录,查找指定后缀文件

方法一:

import os

def get_files(dir_path,suffix,res):
    file_list = os.listdir(dir_path)
    for obj in file_list:
        new_path = os.path.join(dir_path,obj)
        if os.path.isfile(new_path):
            if obj.endswith(suffix):
                res.append(os.path.join(dir_path,obj))
        elif os.path.isdir(new_path):
            get_files(new_path,suffix,res)

if __name__ == '__main__':
    res_list = []
    get_files('./','.pyc',res_list)
    print(res_list)

方法二:

import os

def get_files(search_dir,suffix):
    res = []
    for root, dirs, files in os.walk(search_dir):
        for file in files:
            name,suf = os.path.splitext(file)
            if suf == suffix:
                print(root)
                res.append(os.path.join(root,file))
    return res

if __name__ == '__main__':
    res = get_files('./','.pyc')
    print(res)

方法三:

from glob import iglob

def get_files(dir_path,suffix,res):
    for file in iglob(f"{dir_path}/**/*{suffix}",recursive=True):
        res.append(file)

if __name__ == '__main__':
    res_list = []
    get_files('./','.pyc',res_list)
    print(res_list)

你可能感兴趣的:(simple_example)