今天小編就爲大家分享一篇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 文件查找及內容匹配方法就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持神馬文庫。