python 文件查找及内容匹配方法

yipeiwu_com6年前Python基础

需求:程序开发中有大量的接口,但在实际的使用中有一部分是没有使用的,在开发的程序中匹配这些接口名,找到哪些接口从没有使用过。将这些没有使用过的接口名保存下来。

代码结构:

结构解析:

1、find.py 是文件查找及匹配程序

2、input_files.txt是待匹配内容

文件格式如下:

3、result.txt 用于存放查找结果

格式同上

4、text.txt 用于测试的文档(可忽略)

实际代码:

find.py

#!/usr/bin/python
# -*- coding: UTF-8 -*-
import os, re, datetime


class Find(object):
 def __init__(self, root, input_file):
  """
    --初始化
  """
  self.root = root # 文件树的根
  self.input_files = [] # 待查询的字符串集合
  self.files = [] # 待匹配的文件集合
  self.current = 0 # 正在匹配的文件集合的位置

  f = file(input_file, "r")
  old_content = f.read()
  f.close()
  self.input_files = old_content.split('\n') # 将待匹配字符串保存在数组中

 @staticmethod
 def find_file(self):
  """
  --查找文件,即遍历文件树将查找到的文件放在文件集合中
  :return:
  """
  # python中的walk方法可以查找到所给路径下的所有文件和文件夹,这里只用文件
  for root, dirs, files in os.walk(self.root, topdown=True):
   for name in files:
    self.files.append(os.path.join(root, name))
    #  print(os.path.join(root, name))
    # for name in dirs:
    #  print(os.path.join(root, name))

 @staticmethod
 def walk(self):
  """
  --逐一查找,并将结果存入result.txt文件中
  :param self:
  :return:
  """
  for item1 in self.files:
   Find.traverse_file(self, item1)
  try:
   result = ''
   for item3 in self.input_files:
    result += item3 + '\n'
   f = file("./result_files.txt", "w")
   f.write(result)
   f.close()
  except IOError, msg:
   print "Error:", msg
  else:
   print "OK"

 @staticmethod
 def traverse_file(self, file_path):
  """
  --遍历文件,匹配字符串
  :return:
  """
  f = file(file_path, "r")
  file_content = f.read()
  f.close()
  input_files = []
  for item2 in self.input_files:
   if item2:
    # 正则匹配,不区分大小写
    searchObj = re.search(r'(.*)' + item2 + '.*', file_content, re.M | re.I)
    if searchObj:
     continue
    else:
     input_files.append(item2)
  self.input_files = input_files


if __name__ == "__main__":

 print datetime.datetime.now()
 findObj = Find('F:\\projects', "./input_files.txt")
 findObj.find_file(findObj)
 findObj.walk(findObj)
 print datetime.datetime.now()

以上这篇python 文件查找及内容匹配方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

11月编程语言排行榜 Python逆袭C#上升到第4

11月编程语言排行榜 Python逆袭C#上升到第4

TIOBE 11 月编程语言排行榜,Python 逆袭C# 曾经有一段时间,脚本语言因其易于编写和易于运行的特性,被预测在未来将发展强大。因此,Perl,Python,PHP 和 Rub...

如何用C代码给Python写扩展库(Cython)

如何用C代码给Python写扩展库(Cython)

之前一篇文章里提到了利用Cython来编译Python,这次来讲一下如何用Cython给Python写扩展库。 两种语言混合编程,其中最重要的是类型的传递。 我们用一个简单的例子进行入门...

python实现ftp客户端示例分享

复制代码 代码如下:#!/usr/bin/python#coding:utf-8#write:JACK#info:ftp exampleimport ftplib, socket, os...

Python基于聚类算法实现密度聚类(DBSCAN)计算【测试可用】

Python基于聚类算法实现密度聚类(DBSCAN)计算【测试可用】

本文实例讲述了Python基于聚类算法实现密度聚类(DBSCAN)计算。分享给大家供大家参考,具体如下: 算法思想 基于密度的聚类算法从样本密度的角度考察样本之间的可连接性,并基于可连接...

Python利用operator模块实现对象的多级排序详解

前言 最近在工作中碰到一个小的排序问题,需要按嵌套对象的多个属性来排序,于是发现了Python里的operator模块和sorted函数组合可以实现这个功能。本文介绍了Python用op...