Replacing a phrase in a `.doc` file with python

273 Views Asked by At

I have a .doc file that contains text, I need to replace a particular phrase with another one in this document.

I tried using python-docx but it doesn't support the .doc format. I also tried using the normal string replace functionality but it's corrupting the doc file

with open("input.doc") as r:
   text = r.read().replace("old text", "new text")
with open("output.doc", "w") as w:
   w.write(text)

I can't change the extension of the file and I want to do it in python.

1

There are 1 best solutions below

0
Felipe Cavalcante da Rocha On

I think you must open the files in binary mode:

open("input.doc", "rb")

and

open("output.doc", "wb")

You must change the "replace" method to adequate it to binary mode.