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? -


as new python programming, want open .docx file, parse it, find occurrence of particular string in multiple places , adding 2 lines after in whole document. how can these thing using python script?

you follows using win32com:

import win32com.client  search_for = "this text in file" add_lines = "^pline1^pline2^pline3"     # ^p creates 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 colour of replacement text add following before find.execute:

find.replacement.font.color = 255       # wdcolorred 

a full list of standard word colours listed on microsoft site.


Comments