How can I open a docx file, find a particular string occurring at multiple places and add two lines after that in the whole document using python?
Question: As I am new to the python programming, I want to open a .docx file, parse it,
find occurrence of particular string in multiple places and then adding two
lines after that in whole document. How can i do these thing using python
script?


Answer: You could do this as follows using `win32com`:

    
    
    import win32com.client
    
    search_for = "This is some text in my file"
    add_lines = "^pLine1^pLine2^pLine3"     # ^p creates a new line
    
    word = win32com.client.Dispatch("Word.Application")
    word.Visible = False
    word.DisplayAlerts = False
    doc = word.Documents.Open(r'c:\my_folder\my_file.docx')
    const = win32com.client.constants
    
    find = doc.Content.Find 
    find.ClearFormatting()
    find.Replacement.ClearFormatting()
    find.Execute(Forward=True, Replace=const.wdReplaceAll, FindText=search_for, ReplaceWith=search_for+add_lines)
    
    word.ActiveDocument.SaveAs(r'c:\my_folder\my_file_output.docx')
    word.Quit() 
    

To change the colour of the replacement text you could also add the following
before the `find.Execute`:

    
    
    find.Replacement.Font.Color = 255       # wdColorRed
    

A full list of standard Word colours is listed on the [Microsoft
site](https://msdn.microsoft.com/en-us/library/office/ff196272.aspx).

