查找某个目录下包含有某个关键字的所有文件夹以及子文件夹里的文件名

本文中的循环可以省略,只用一条语句实现,为了理解简单,扩展开写的,如下

#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)

你可能感兴趣的:(python开发)