python 在一個文件夾的所有文件中查找關鍵字


python 在一個文件夾的所有文件中查找關鍵字

 

import os,shutil
import re

key='Hello'
re_parttern=re.compile(r''+key,re.DOTALL)

#返回含有目標文字的文件名
filepath='./test/'

def get_file(filepath):
    filelist=os.listdir(filepath)
    aim_files=[]
    for filename in filelist:
        filename1=os.path.splitext(filename)[1] #獲取文件后綴
        if filename1 in ['.py','.txt','.doc','.docx']:
            #匹配

            flag=match_content(filename)
            if flag==True:
                aim_files.append(filename)
                
    return aim_files


def match_content(filename):
    flag=False
    fstr=''
    #只讀模式打開並匹配
    fullpath=os.path.join(filepath,filename)
    fp=open(fullpath,'r')
    content=fp.readlines()
    
    for c in content:
        fstr+=c.replace('/n',' ')
    aim=re.findall(re_parttern,fstr)

    if aim !=None:
        flag=True

    fp.close()
    return flag



if __name__ =="__main__":
    result=get_file(filepath)
    print(result)

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM