我們經常會遇到在不同的 Word 文件中的需要做相同的文字替換,若是一個一個
文件操作,會花費大量時間 。 本節案例可以找出指定目錄中的所有 Word 文件(包含
子目錄),並對每一個文件進行指定的文字替換操作。
案例要求
把 replace 目錄(包含子目錄〉下所有 Word 文件中自甘“方法”都替換為“ method ”
下圖中左圖為 replace\s ubReplace\e lse.docx 文件替換后的結果,右圖為在命令窗口中
顯示的所有進行過替換操作的 Word 文件。
import os
from win32com import client
from win32com.client import constants
word = client.gencache.EnsureDispatch('Word.Application')
word.Visible = 0
word.DisplayAlerts = 0
runpath = "F:\\pythonBase\\pythonex\\ch08\\replace" #獲取replace文件夾的路徑
tree = os.walk(runpath) #取得目錄樹
print("所有 Word 文件:")
for dirname, subdir, files in tree:
allfiles = []
for file in files: # 取得所有.docx .doc文件,存入allfiles列表中
ext = file.split(".")[-1] #取得文件名后綴
if((ext=="docx") or (ext=="doc")): #取得所有.docx .doc文件
allfiles.append(dirname + '\\' + file) #加入allfiles列表
if(len(allfiles) > 0): #如果有符合條件的文件
for dfile in allfiles:
print(dfile)
doc = word.Documents.Open(dfile) #打開文件
word.Selection.Find.ClearFormatting()
word.Selection.Find.Replacement.ClearFormatting()
word.Selection.Find.Execute("方法",False,False,False,False,False,True,constants.wdFindContinue,False,"method",constants.wdReplaceAll)
doc.Close()
word.Quit()
