平台:Win764 bit,IDLE Python 3.4.0
经常有这样的需求:在一个文本文件里查找特定字符串,这很好实现,用任何文本查看工具几乎都可以做到。而有的时候,想查找一个文件夹下的所有文本文件(特定后缀),我就遇到了这样的问题:想找到Blender的源代码中关于SPH的实现代码。于是写了下面的简单程序:
#!/usr/bin/env python3importosdefSearch(rootDir, suffixes, arg):forlistsinos.listdir(rootDir):
path=os.path.join(rootDir, lists)ifos.path.isfile(path):ifpath.endswith(suffixes):try:
with open(path, encoding='utf_8') as fh:
lineNum=0forlineinfh:
lineNum+= 1ifarginline:PRint(lineNum,':', path,'\n', line)
fh.close()except:print('error:', path,'\n')ifos.path.isdir(path):
Search(path, suffixes, arg)
Search(r'D:\blender-2.70', ('.c','.cpp','.h','.hpp'),'SPH')
程序虽小,但很实用,运行结果如下:
参考文献:
官网,https://www.python.org/,文档,https://docs.python.org/3/(IDLE help);Python绝对简明教程,http://wiki.woodpecker.org.cn/moin/PyAbsolutelyZipManual;简明Python教程,http://woodpecker.org.cn/abyteofpython_cn/chinese/。