首页 > 学院 > 开发设计 > 正文

Python实现对文件夹内文本文件递归查找

2019-11-14 17:48:25
字体:
来源:转载
供稿:网友

 

平台:Win7 64 bit,IDLE Python 3.4.0

 

经常有这样的需求:在一个文本文件里查找特定字符串,这很好实现,用任何文本查看工具几乎都可以做到。而有的时候,想查找一个文件夹下的所有文本文件(特定后缀),我就遇到了这样的问题:想找到Blender的源代码中关于SPH的实现代码。于是写了下面的简单程序:

#!/usr/bin/env python3import osdef Search(rootDir, suffixes, arg):       for lists in os.listdir(rootDir):               path = os.path.join(rootDir, lists)        if os.path.isfile(path):            if path.endswith(suffixes):                try:                    with open(path, encoding='utf_8') as fh:                        lineNum = 0                        for line in fh:                            lineNum += 1                            if arg in line:                                PRint(lineNum, ':', path, '/n', line)                        fh.close()                except:                    print('error: ', path, '/n')        if os.path.isdir(path):            Search(path, suffixes, arg)Search(r'D:/blender-2.70', ('.c','.cpp','.h','.hpp'), 'SPH ')

程序虽小,但很实用,运行结果如下:

 

参考文献

  1. 官网,https://www.python.org/,文档,https://docs.python.org/3/(IDLE help);
  2. Python绝对简明教程,http://wiki.woodpecker.org.cn/moin/PyAbsolutelyZipManual;
  3. 简明Python教程,http://woodpecker.org.cn/abyteofpython_cn/chinese/

 


发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表