I need to change some custom properties values in many files. Here is an example of code – how I do it for a single file:
import win32com.client
MSWord = win32com.client.Dispatch("Word.Application")
MSWord.Visible = False
doc = MSWord.Documents.Open(file)
doc.CustomDocumentProperties('Some Property').Value = 'Some New Value'
doc.Save()
doc.Close()
MSWord.Quit()
Running the same code for "Excel.Application" (with minor changes – just to make it work) gives me excellent result. However when I’m using doc.Save() or doc.SaveAs(same_file) for MSWord it silently fails. I don’t know why, but changes are not saved.
Now my workaround is to use SaveAs to a different file, it also works good. But I want to understand why I have such strange behaviour for MSWord files and how it can be fixed?
Edit: I changed my code, not to misdirect people with silent fail cause of try/except.
However, thanks to all of them for finding that defect in my code 🙂
You were using the
CustomDocumentPropertiesin the wrong way, and as other people pointed out, you could not see it, because you were swallowing the exception.Moreover – and here I could not find anything in the documentation – the
Savedproperty was not reset while changing properties, and for this reason the file was not changed.This is the correct code:
Note: there is no error handling, and it is definitely not of production quality, but it should be enough for you to implement your functionality.
Finally, I am guessing the values of the property types (and for the string type the guess is correct) but for the others there could be some issue.