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设计】。

相关文章

使用Python的Twisted框架构建非阻塞下载程序的实例教程

使用Python的Twisted框架构建非阻塞下载程序的实例教程

第一个twisted支持的诗歌服务器 尽管Twisted大多数情况下用来写服务器代码,但为了一开始尽量从简单处着手,我们首先从简单的客户端讲起。 让我们来试试使用Twisted的客户端。...

Pandas中Series和DataFrame的索引实现

正文 在对Series对象和DataFrame对象进行索引的时候要明确这么一个概念:是使用下标进行索引,还是使用关键字进行索引。比如list进行索引的时候使用的是下标,而dict索引的时...

Python中几种属性访问的区别与用法详解

起步 在Python中,对于一个对象的属性访问,我们一般采用的是点(.)属性运算符进行操作。例如,有一个类实例对象foo,它有一个name属性,那便可以使用foo.name对此属性进行...

纯用NumPy实现神经网络的示例代码

纯用NumPy实现神经网络的示例代码

摘要: 纯NumPy代码从头实现简单的神经网络。 Keras、TensorFlow以及PyTorch都是高级别的深度学习框架,可用于快速构建复杂模型。前不久,我曾写过一篇文章...

关于Python3 lambda函数的深入浅出

我们常常看到一个这样的表达式  A=lambda x:x+1 可能会一头雾水不知道怎么计算 最基本的理解就是 def A(x): return x+1 但是理解程序不会将一个表...