How to write to a open Word Document

631 views Asked by At

I wish to be able to write to an open word document using python-docx. However this throws a IOError: [Errno 13] Permission denied: 'test.docx' which i had kind of suspected due to similar cases in the past, but i would like to be able to alter the document without having to close and open it which takes word a long time, for a relatively fast and short operation (appending bibliographies to the end of word doc ie assignment).

Opening and reading is perfectly fine and easy (thus that access is granted), however, I am not able to actually save the file (with the same name of course as the user must not notice) as this throws the error. When the file is not open in word, the error goes away, but this is not acceptable (to close and reopen continuously).

Perhaps there is another way to save documents in word with python-docx? One that involves appending instead of destroying and recreating i think would be much better (such as when one accesses a .txt file with "with" or "read".

It would be much better to be able to somehow add text to a word document while it is open, resulting in a better and faster experience for the user as well.

1

There are 1 answers

0
scanny On

This error is coming from the operating system (Windows it sounds like), and well it should.

The operation you're asking for would only make sense via control of the Word application in which the document is open. This can be accomplished via Visual Basic, i.e. a Word macro.

The reason it doesn't make sense when using a separate program, python-docx in this case, is that the changes you make would not be visible in Word. It doesn't automatically sense changes to the file and reload it. Worse, the changes you made would be lost when the user saves their document; the document Word has in memory would overwrite the changed version you made.

This is why it's very sensible for Windows to refuse to open the file for you, to prevent "lost changes", which is why an operating system has file locking.