Why can saving a MSWord document fail silently?

I need to change some values ​​of custom properties in many files. Here is a sample code - how do I do this 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 for it to work) gives an excellent result. However, when I use doc.Save()or doc.SaveAs(same_file)for MSWord, it silently fails. I don’t know why, but the changes are not saved.

Now my workaround is to use SaveAsfor another file, it also works well. But I want to understand why I have such strange behavior for MSWord files and how can I fix this?

. , try/except. , :)

+3
4

CustomDocumentProperties, , , , .

- - Saved reset , .

:

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()

: , , , .
, ( ), .

+3

, Value . , try - except , , . , , bare except .

+1

(a) ,

(b) Verify that the code is caught using a COMException

(C) you gracefully complete excel / words while creating multiple documents

Darknight

0
source

It fails because you are ignoring errors ( except: pass).

The most common reason that a Word file usually crashes normally is because it opens in Word.

0
source

Source: https://habr.com/ru/post/1716212/


All Articles