Replace Text in Multiple Word Documents with Python
Find and replace across a whole folder of Word documents, driven from Python. pywin32 opens each file through Word itself, runs Word’s own Find and Replace on the main text, and a second loop handles text boxes. Formatting and images stay intact. Windows only, since it relies on the Word COM interface.
Requirements
The script needs Windows, Microsoft Word and the pywin32 package, because it drives Word itself through COM. I tried python-docx first, but it dropped images and broke formatting in my documents; letting Word do the replacing avoids both.
pip install pywin32
Imports and folders
The script imports Path from pathlib (part of Python) for the file paths and win32com.client from pywin32 to control Word.
from pathlib import Path
import win32com.client
The Word files to change go into an input folder next to the script. The script creates an output folder for the changed copies.
current_dir = Path(__file__).parent if "__file__" in locals() else Path.cwd()
input_dir = current_dir / "input"
output_dir = current_dir / "output"
output_dir.mkdir(parents=True, exist_ok=True)
Find and replace settings
Set the text to find and its replacement, here the year 2022 to 2023. The two numbers are Word’s own constants: wd_replace = 2 replaces every match, and wd_find_wrap = 1 continues the search through the whole document.
find_str = "2022"
replace_with = "2023"
wd_replace = 2 # 2=replace all occurences, 1=replace one occurence, 0=replace no occurences
wd_find_wrap = 1 # 2=ask to continue, 1=continue search, 0=end if search range is reached
Open Word
Word starts in the background: Visible = False hides the window and DisplayAlerts = False keeps dialogs from stopping the script. DispatchEx starts its own Word instance instead of taking over a Word window you have open.
word_app = win32com.client.DispatchEx("Word.Application")
word_app.Visible = False
word_app.DisplayAlerts = False
The loop
The loop opens every .doc and .docx file in the input folder, runs Word’s Find and Replace on the main text, replaces matches in text boxes, saves a copy to the output folder and closes the document. Here is the complete script from the repository:
from pathlib import Path # core python module
import win32com.client # pip install pywin32
# Path settings
current_dir = Path(__file__).parent if "__file__" in locals() else Path.cwd()
input_dir = current_dir / "input"
output_dir = current_dir / "output"
output_dir.mkdir(parents=True, exist_ok=True)
# Find & replace
find_str = "2022"
replace_with = "2023"
wd_replace = 2 # 2=replace all occurences, 1=replace one occurence, 0=replace no occurences
wd_find_wrap = 1 # 2=ask to continue, 1=continue search, 0=end if search range is reached
# Open Word
word_app = win32com.client.DispatchEx("Word.Application")
word_app.Visible = False
word_app.DisplayAlerts = False
for doc_file in Path(input_dir).rglob("*.doc*"):
# Open each document and replace string
word_app.Documents.Open(str(doc_file))
# API documentation: https://learn.microsoft.com/en-us/office/vba/api/word.find.execute
word_app.Selection.Find.Execute(
FindText=find_str,
ReplaceWith=replace_with,
Replace=wd_replace,
Forward=True,
MatchCase=True,
MatchWholeWord=False,
MatchWildcards=True,
MatchSoundsLike=False,
MatchAllWordForms=False,
Wrap=wd_find_wrap,
Format=True,
)
# -- Replace str in shapes
# VBA SO reference: https://stackoverflow.com/a/26266598
# Loop through all the shapes
for i in range(word_app.ActiveDocument.Shapes.Count):
if word_app.ActiveDocument.Shapes(i + 1).TextFrame.HasText:
words = word_app.ActiveDocument.Shapes(i + 1).TextFrame.TextRange.Words
# Loop through each word. This method preserves formatting.
for j in range(words.Count):
# If a word exists, replace the text of it, but keep the formatting.
if word_app.ActiveDocument.Shapes(i + 1).TextFrame.TextRange.Words.Item(j + 1).Text == find_str:
word_app.ActiveDocument.Shapes(i + 1).TextFrame.TextRange.Words.Item(j + 1).Text = replace_with
# Save the new file
output_path = output_dir / f"{doc_file.stem}_replaced{doc_file.suffix}"
word_app.ActiveDocument.SaveAs(str(output_path))
word_app.ActiveDocument.Close(SaveChanges=False)
word_app.Application.Quit()
Two parameters deserve a closer look. MatchWildcards=True turns on Word’s wildcard search, so characters such as ? and * in your search text act as wildcards; set it to False for a plain search. MatchCase=True means 2022 matches but a word in different capitals would not.
The originals are never touched: each result is saved as a copy with _replaced in the name. When the loop is done, Quit closes the Word instance.

Text boxes
Word’s Find and Replace on the selection skips text boxes, which are shapes. The second loop, adapted from a VBA answer on Stack Overflow, goes through every shape that has text and replaces matching words one by one, which keeps their formatting.
Limits
The script does not reach headers, footers or footnotes. The Find call works on the main document text, and the second loop only on shapes in the main text. Text in headers and footers lives in separate story ranges, so you need an extra loop over ActiveDocument.StoryRanges if your documents carry the year or a name there.
The shape loop compares whole words, so it replaces 2022 but not FY2022. Test the script on copies of a few files first. If you need to create new documents from Excel instead of editing existing ones, see generating Word documents from an Excel list; for the same kind of find and replace in spreadsheets, see find and replace values in multiple Excel files.
