回答OSChina网站中的一个提问,提问者的代码看着难受。经常能看到Python代码,却不Pythonic(python思维方式)!
#-*- coding: utf-8 -*-
import os, os.path
def get_all_files(fdir, fext):
""" 递归找出目录和子目录中指定扩展名的文件 """
for f in os.listdir(fdir):
f = os.path.join(fdir, f)
if os.path.isdir(f):
for ff in get_all_files(f, fext):
yield ff
elif os.path.isfile(f) and f.endswith(fext):
yield f
if __name__ == "__main__":
for d in os.listdir("."):
if os.path.isfile(d) or d.startswith("."):
continue
fs = [f for f in get_all_files(d, ".py")]
# listdir返回的乱序,如要排序,请在这里处理
print d, "\n", len(fs), "\n", fs, "\n"