運用:os.walk遞迴搜尋,檔案內文
前天發的錯誤版本(已刪除),掉入os.walk天坑,和python迴圈不明確的陷阱內撞牆,今天本文是更正版。
套件:讀舊版word .doc  先 pip install pypiwin32
讀word .docx 請 pip install python-docx
import os, sys, docx
from win32com import client
流程:
舊版word .doc讀檔略為麻煩,解釋一下,其它請download source code
#--- 找檔案內容,有無 keyword 之存在
# 參數 afile 檔名  keyword 要搜尋的字
# 傳回: found : key:找到的位置 / value:該段落文字  
def findDoc(afile, keyword):
    found = dict()
    try:
        # 開啟舊版word檔的方式  .doc
        word = client.gencache.EnsureDispatch('Word.Application')
        word.Visible = 0
        word.DisplayAlerts = 0
        doc = word.Documents.Open(afile)
        paras = doc.Paragraphs
        n = 0 
        print(f'searching ... {afile}' )              
        for p in paras:
            n += 1  # 段落數
            # 如果該段落有此一keyword
            if keyword in p.Range.Text:
                tmp = f'檔案: {afile} 第{n}行找到< {keyword} >'
                # dict 新增一筆 key:找到的位置 / value:該行文字
                found[tmp] = p.Range.Text
        doc.Close()   # 關檔步驟,不可少         
    except:
        err = f'檔案: {afile} 讀取錯誤'
        found[0] = err
        
    return found     
從console執行,會詢問起始資料夾、keyword、檔案類型
搜尋後結果存檔,打開來看看
特別注意:因為連續開啟、關閉多個word檔案,如果在除錯執行中程式中斷了,會造成word不正常關閉情況,還在背景運作。如果這時又重新測試程式,常常就卡住不動了。
請去"工作管理員"把word關檔。
或是出現這個提示時,按yes