python实现搜索指定目录下文件及文件内搜索指定关键词的方法


Posted in Python onJune 28, 2015

本文实例讲述了python实现搜索指定目录下文件及文件内搜索指定关键词的方法。分享给大家供大家参考。具体实现方法如下:

#!/usr/bin/python -O
# -*- coding: UTF-8 -*-
"""
Sucht rekursiv in Dateiinhalten und listet die Fundstellen auf.
"""
__author__ = "Jens Diemer"
__license__ = """GNU General Public License v2 or above -
 http://www.opensource.org/licenses/gpl-license.php"""
__url__ = "http://www.jensdiemer.de"
__version__ = "0.1"
import os, time, fnmatch
class search:
  def __init__(self, path, search_string, file_filter):
    self.search_path = path
    self.search_string = search_string
    self.file_filter = file_filter
    print "Search '%s' in [%s]..." % (
      self.search_string, self.search_path
    )
    print "_" * 80
    time_begin = time.time()
    file_count = self.walk()
    print "_" * 80
    print "%s files searched in %0.2fsec." % (
      file_count, (time.time() - time_begin)
    )
  def walk(self):
    file_count = 0
    for root, dirlist, filelist in os.walk(self.search_path, followlinks=True):
      for filename in filelist:
        for file_filter in self.file_filter:
          if fnmatch.fnmatch(filename, file_filter):
            self.search_file(os.path.join(root, filename))
            file_count += 1
    return file_count
  def search_file(self, filepath):
    f = file(filepath, "r")
    content = f.read()
    f.close()
    if self.search_string in content:
      print filepath
      self.cutout_content(content)
  def cutout_content(self, content):
    current_pos = 0
    search_string_len = len(self.search_string)
    for i in xrange(max_cutouts):
      try:
        pos = content.index(self.search_string, current_pos)
      except ValueError:
        break
      content_window = content[ pos - content_extract : pos + content_extract ]
      print ">>>", content_window.encode("String_Escape")
      current_pos += pos + search_string_len
    print
if __name__ == "__main__":
  search_path = r"c:\texte"
  file_filter = ("*.py",) # fnmatch-Filter
  search_string = "history"
  content_extract = 35 # Gr��e des Ausschnittes der angezeigt wird
  max_cutouts = 20 # Max. Anzahl an Treffer, die Angezeigt werden sollen
  search(search_path, search_string, file_filter)

希望本文所述对大家的Python程序设计有所帮助。

Python 相关文章推荐
Python下的Mysql模块MySQLdb安装详解
Apr 09 Python
Python的SQLalchemy模块连接与操作MySQL的基础示例
Jul 11 Python
一个基于flask的web应用诞生 flask和mysql相连(4)
Apr 11 Python
centos6.4下python3.6.1安装教程
Jul 21 Python
人生苦短我用python python如何快速入门?
Mar 12 Python
Python常用字符串替换函数strip、replace及sub用法示例
May 21 Python
使用python进行文本预处理和提取特征的实例
Jun 05 Python
python绘制直线的方法
Jun 30 Python
Flask配置Cors跨域的实现
Jul 12 Python
python打开使用的方法
Sep 30 Python
python3.7 openpyxl 在excel单元格中写入数据实例
Sep 01 Python
Ubuntu20下的Django安装的方法步骤
Jan 24 Python
分析用Python脚本关闭文件操作的机制
Jun 28 #Python
python实现linux下使用xcopy的方法
Jun 28 #Python
自动化Nginx服务器的反向代理的配置方法
Jun 28 #Python
python读取TXT到数组及列表去重后按原来顺序排序的方法
Jun 26 #Python
在Python中使用zlib模块进行数据压缩的教程
Jun 26 #Python
Python中的zipfile模块使用详解
Jun 25 #Python
Python实现保证只能运行一个脚本实例
Jun 24 #Python
You might like
PHP开发中常用的8个小技巧
2008/08/27 PHP
PHP学习笔记之二 php入门知识
2011/01/12 PHP
中高级PHP程序员应该掌握哪些技术?
2016/09/23 PHP
PHP利用缓存处理用户注册时的邮箱验证,成功后用户数据存入数据库操作示例
2019/12/31 PHP
学习jquery之一
2007/04/27 Javascript
设为首页加入收藏兼容360/火狐/谷歌/IE等主流浏览器的代码
2013/03/26 Javascript
Google Map V3 绑定气泡窗口(infowindow)Dom事件实现代码
2013/04/26 Javascript
jquery实现动静态条形统计图
2015/08/17 Javascript
基于JS实现textarea中获取动态剩余字数的方法
2016/05/25 Javascript
关于Jquery中的bind(),on()绑定事件方式总结
2016/10/26 Javascript
vue实现提示保存后退出的方法
2018/03/15 Javascript
Angular.JS读取数据库数据调用完整实例
2019/07/02 Javascript
antd-mobile ListView长列表的数据更新遇到的坑
2020/04/08 Javascript
vue项目中openlayers绘制行政区划
2020/12/24 Vue.js
[01:14:41]DOTA2-DPC中国联赛定级赛 iG vs Magma BO3第一场 1月8日
2021/03/11 DOTA
Python内置数据类型详解
2014/08/18 Python
python中pandas.DataFrame对行与列求和及添加新行与列示例
2017/03/12 Python
python基本语法练习实例
2017/09/19 Python
python3 pandas 读取MySQL数据和插入的实例
2018/04/20 Python
在python中安装basemap的教程
2018/09/20 Python
使用Python机器学习降低静态日志噪声
2018/09/29 Python
使用numba对Python运算加速的方法
2018/10/15 Python
树莓派与PC端在局域网内运用python实现即时通讯
2019/06/22 Python
Python正则表达式学习小例子
2020/03/03 Python
什么是python的自省
2020/06/21 Python
对pytorch中x = x.view(x.size(0), -1) 的理解说明
2021/03/03 Python
Python解析m3u8拼接下载mp4视频文件的示例代码
2021/03/03 Python
新西兰优惠网站:Treat Me
2019/07/04 全球购物
C语言中一个结构不能包含指向自己的指针吗
2012/05/25 面试题
应届生保险求职信
2013/11/11 职场文书
大学团日活动新闻稿
2014/09/10 职场文书
银行招聘自荐信
2015/03/06 职场文书
2015年人力资源工作总结
2015/04/08 职场文书
安全教育主题班会总结
2015/08/14 职场文书
申论不会写怎么办?教您掌握这6点思维和原则
2019/07/17 职场文书
oracle DGMGRL ORA-16603报错的解决方法(DG Broker)
2021/04/06 Oracle