第一种方法:

import os

def get_files(dir,suffix):
    res = []
    for root,dirs,files in os.walk(dir):
        for filename in files:
            name,suf = os.path.splitext(filename)
            if suf == suffix:
                res.append(os.path.join(root,filename))
    print(res)
get_files("./",'.pyc')

第二种方法:

import os
def pick(obj):
    if obj.endswith(".pyc"):
        print(obj)
def scan_path(ph):
    file_list = os.listdir(ph)
    for obj in file_list:
        if os.path.isfile(obj):
            pick(obj)
        elif os.path.isdir(obj):
            scan_path(obj)
if __name__=='__main__':
    path = input('输入目录')
    scan_path(path)

第三种方法

from glob import iglob
def func(fp, postfix):
    for i in iglob(f"{fp}/**/*{postfix}", recursive=True):
        print(i)
if __name__ == "__main__":
    postfix = ".pyc"
    func("K:\Python_script", postfix)
评论 (0)