本文中的循环可以省略,只用一条语句实现,为了理解简单,扩展开写的,如下
#coding = utf-8 import os #from functools import reduce def search(path,s): #result = [filename for t in os.walk(path) for filename in t[2] if s in os.path.splitext(filename)[0]] result = [] for t in os.walk(path): #返回的是root,dirs,files for filename in t[2]: #t[2]指的就是files if s in os.path.splitext(filename)[0]: #test.txt [0]为test [1]为.txt 文件名和扩展名 result.append(filename) return result if __name__ == '__main__': result = search('D:py','learning') print(result)