没有合适的资源?快使用搜索试试~ 我知道了~
温馨提示
试读
1页
本文实例讲述了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/g
资源推荐
资源详情
资源评论
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: exte"
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仿evething的文件搜索器实例代码python实现搜索文本文件内容脚本Python实现的本地文件搜索
功能示例【测试可用】python实现搜索本地文件信息写入文件的方法python开发之基于thread线程搜索本地文件的方法python
实现的用于搜索文件并进行内容替换的类实例Python3搜索及替换文件中文本的方法python使用正则搜索字符串或文件中的浮
点数代码实例python将多个文本文件合并为一个文本的代码(便于搜索)python 搜索大文件的实例代码
资源评论
weixin_38734008
- 粉丝: 12
- 资源: 916
上传资源 快速赚钱
- 我的内容管理 展开
- 我的资源 快来上传第一个资源
- 我的收益 登录查看自己的收益
- 我的积分 登录查看自己的积分
- 我的C币 登录后查看C币余额
- 我的收藏
- 我的下载
- 下载帮助
安全验证
文档复制为VIP权益,开通VIP直接复制
信息提交成功