提取目錄下c檔案包含關鍵字的行,c編程輔助用。分享。
import os,re
class SearchFile(object):
def __init__(self,path='.'):
self._path=path
self.abspath=os.path.abspath(self._path) # 默認當前目錄
def findLines(self,keyword,root):
filelist=[]
for root,dirs,files in os.walk(root):
for name in files:
fileName=re.match(".*\.c$",os.path.join(root, name))
if fileName:
fitfile=filelist.append(os.path.join(root, name))
print('...........................................')
for filepath in filelist:
if os.path.isfile(filepath):
#打開檔案查找是否存在對應關鍵字
fp = open(filepath, 'r')
try:
lines = fp.readlines()
except:
print("打開檔案"+filepath+"例外")
else:
k = 0
for strtemp in lines:
out = re.match(".*"+keyword+".*",strtemp)
if out :
print(strtemp)
def __call__(self):
while True:
workpath=input('查找當前目錄? Y/N:')
if(workpath == ''):
break
if workpath=='y' or workpath=='Y':
root=self.abspath # 把當前作業目錄作為作業目錄
print('目錄:',root)
#dirlist=os.listdir() # 列出作業目錄下的檔案和目錄
#print(dirlist)
else:
root=input('輸入查找目錄:')
print('目錄:',root)
keyword=input('需要查找的關鍵字,輸入空默認關鍵字\"static const char *\":')
if(keyword==''):
keyword="static const char *"
self.findLines(keyword,root) # 查找帶指定字符的檔案
if __name__ == '__main__':
search = SearchFile()
search()
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/60806.html
上一篇:爬百度搜索指數的代碼,報錯SyntaxError: invalid syntax
下一篇:python切片的一些疑問
