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安装Numpy和matplotlib的方法(推荐)

Python安装Numpy和matplotlib的方法(推荐) 注意: 下载的库名中cp27代表python2.7,其它同理。 在shell中输入import pip; print(p...

Python 变量类型及命名规则介绍

首字母为英文和下划线,其它部分则可以是英文、数字和下划线(即:_),而变量名称是区分大小写,即变量temp与Temp为不同变量。变量的基本用法如下: 复制代码 代码如下:# 例:使用变...

Python中Django 后台自定义表单控件

Python中Django 后台自定义表单控件

在 django 中我们可以在 admin.py 中添加 ModelAdmin,这样就能很方便地在后台进行增删改查的操作。然而,对应 Model 生成的表单,并不友好,我们希望能像前端开...

使用rst2pdf实现将sphinx生成PDF

使用rst2pdf实现将sphinx生成PDF

当初项目文档是用sphinx写的,一套rst下来make html得到一整个漂亮的在线文档。现在想要将文档导出为离线的handbook pdf,于是找到了rst2pdf这个项目,作为sp...

用Python写飞机大战游戏之pygame入门(4):获取鼠标的位置及运动

用Python写飞机大战游戏之pygame入门(4):获取鼠标的位置及运动

目标是拷贝微信的飞机大战,当然拷贝完以后大家就具备自己添加不同内容的能力了。 首先是要拿到一些图片素材,熟悉使用图像处理软件和绘画的人可以自己制作,并没有这项技能的同学只能和我一样从网上...