Reputation: 4500
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 :)
Upvotes: 3
Views: 954
Reputation: 37664
You were using the CustomDocumentProperties
in 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 Saved
property was not reset while changing properties, and for this reason the file was not changed.
This is the correct code:
msoPropertyTypeBoolean = 0
msoPropertyTypeDate = 1
msoPropertyTypeFloat = 2
msoPropertyTypeNumber = 3
msoPropertyTypeString = 4
import win32com.client
MSWord = win32com.client.Dispatch("Word.Application")
MSWord.Visible = False
doc = MSWord.Documents.Open(file)
csp = doc.CustomDocumentProperties
csp.Add('Some Property', False, msoPropertyTypeString, 'Some New Value')
doc.Saved = False
doc.Save()
doc.Close()
MSWord.Quit()
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.
Upvotes: 3
Reputation: 319889
you're saving file only if Value
was successfully changed. May be you could try to remove try
-except
clause and see what is actually happening when you're file is not saved. And, btw, using bare except
is not a good practice.
Upvotes: 1
Reputation: 328770
It fails silently since you ignore errors (except: pass
).
The most common reason why saving a Word file usually fails is that it's open in Word.
Upvotes: 0
Reputation: 2500
(a) Check to see if you have file write access
(b) Make sure you code catches using the COMException
(C) are you gracefully terminating excel/words when creating multiple documents
Darknight
Upvotes: 0