I have to perform a large number of replacements in some documents, and the thing is, I would like to be able to automate that task. Some of the documents contain common str
I like the answers so far;
here's a tested example (slightly modified from here)
that replaces all occurrences of a string in a Word document:
import win32com.client
def search_replace_all(word_file, find_str, replace_str):
''' replace all occurrences of `find_str` w/ `replace_str` in `word_file` '''
wdFindContinue = 1
wdReplaceAll = 2
# Dispatch() attempts to do a GetObject() before creating a new one.
# DispatchEx() just creates a new one.
app = win32com.client.DispatchEx("Word.Application")
app.Visible = 0
app.DisplayAlerts = 0
app.Documents.Open(word_file)
# expression.Execute(FindText, MatchCase, MatchWholeWord,
# MatchWildcards, MatchSoundsLike, MatchAllWordForms, Forward,
# Wrap, Format, ReplaceWith, Replace)
app.Selection.Find.Execute(find_str, False, False, False, False, False, \
True, wdFindContinue, False, replace_str, wdReplaceAll)
app.ActiveDocument.Close(SaveChanges=True)
app.Quit()
f = 'c:/path/to/my/word.doc'
search_replace_all(f, 'string_to_be_replaced', 'replacement_str')