简体   繁体   中英

Unable to find and replace text with win32com .client using python

I am trying to find a text in a word document and replace it some other text. I continue to get the error.

AttributeError: Property '<unknown>.Text' can not be set.

i tried giving the text directly and also by assigning to a variable and it still does not work below is my code.

import win32com.client
import win32api
from datetime import date

path_docx=r'C:\Docs\Approved 10_18_17_TAY.docx'
word = win32com.client.Dispatch('Word.Application')
word.Visible = True
doc=word.Documents.Open(path_docx)
word.Selection.Find.Text = "< DATE >"
word.Selection.Find.Replacement.Text=date.today()
word.Selection.Find.Execute(Replace=word.WdReplace.wdReplaceAll)

It always fails at finding the text

i tried the variables like file_date="< DATE >" and rundate=date.today()

still it did not work.

Any suggestions how to avoid this.

Regards, Ren.

I tried it myself, but there were a lot of small issues.

1) For the wdReplaceAll-constant you need to load the constants separately in Python. This is not well documented and took me a while to find out myself, the firs time I needed it too. You can tell if something is a constant by "wd" for Word or "xl" for Excel prefixes.

2) I used gencache.EnsureDispatch. You can try it with just Dispatch though. I am not sure it will work both ways, but it might.

3) I was not able to get any result when I tried to run it with the 3 .Find commands on separate lines. Once I consolidated it all into the Execute() parameters, it worked.

4) If I pass it the date-object directly, it replaces all occurances of "< DATE >" with "00:00:00" . However if I convert the date-object to string within python and pass that, it works. You might want to change the formatting of the date, though. Checkout the documentation of datetime. Its quite simple.

5) You passed the code a "Selection" object. I am not sure if the default selection is just "everything" when nothing is yet selected. I changed it to iterate over the Paragraphs-object instead. This should yield more consistent results

Heres my code:

import win32com.client as win32
from datetime import date

today = str(date.today())

path_docx='C:\\Scripts\\test.docx' #< obviously you need to change that
word = win32.gencache.EnsureDispatch('Word.Application')
const = win32.constants
word.Visible = True
doc=word.Documents.Open(path_docx)
for paragraph in doc.Paragraphs:
    print(paragraph)
    paragraph.Range.Find.Execute(FindText="< DATE >", ReplaceWith=today, Replace=const.wdReplaceAll)

I hope this works for you. If you have any questions about this solution, let me know.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM