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

yipeiwu_com6年前Python基础

本文实例讲述了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程序设计有所帮助。

相关文章

Django中自定义查询对象的具体使用

自定义查询对象 - objects ①声明一个类EntryManager,继承自models.Manager,并添加自定义函数 ②使用创建的自定义类EntryManager 覆盖Mo...

python面试题Python2.x和Python3.x的区别

下面看下python2.x和python3.x的区别 1.大环境不同   python2.x:源码重复,不规范   python3.x:整合源码,更清晰优美简单  2.默认编码...

python set集合使用方法解析

这篇文章主要介绍了python set集合使用方法解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 定义 定义:在{}中用逗号隔开...

Python实现脚本锁功能(同时只能执行一个脚本)

Python实现脚本锁功能(同时只能执行一个脚本)

1. 文件锁 脚本启动前检查特定文件是否存在,不存在就启动并新建文件,脚本结束后删掉特定文件。 通过文件的判断来确定脚本是否正在执行。 方法实现也比较简单,这里以python脚本为例...

Python解析xml中dom元素的方法

本文实例讲述了Python解析xml中dom元素的方法。分享给大家供大家参考。具体实现方法如下: 复制代码 代码如下:from xml.dom import minidom try: &...