I am unable to open a word file using pywin32. I have been trying to find tutorials for pywin32 but none of the code works. The location of the word document is C:\Users\User\Documents\python progs\misc\formatting for isn.
import win32com.client as win32
word = win32.gencache.EnsureDispatch('Word.Application')
word.Visible = False
word.Documents.Open('C:\\sectarianism.doc')
Traceback (most recent call last):
File "C:\Users\User\Documents\python progs\misc\formatting for isn\formatting.py", line 5, in <module>
word.Documents.Open('C:\\sectarianism.doc')
File "C:\Python25\lib\site-packages\win32com\gen_py\00020905-0000-0000-C000-000000000046x0x8x4\Documents.py", line 96, in Open
, Visible, OpenAndRepair, DocumentDirection, NoEncodingDialog, XMLTransform
com_error: (-2147352567, 'Exception occurred.', (0, u'Microsoft Word', u'This file could not be found.\r (C:\\sectarianism.doc)', u'C:\\Program Files\\Microsoft Office\\Office12\\1033\\WDMAIN11.CHM', 24654, -2146823114), None)
>>>
You need to open the file from the correct location.
You might try this:
import win32com.client as win32
import os
word = win32.gencache.EnsureDispatch('Word.Application')
word.Visible = False
doc_path = os.path.join('c:', os.sep, 'Users', 'User', 'Documents', 'python', 'progs', 'misc', 'formatting for isn', 'sectarianism.doc')
doc = word.Documents.Open(doc_path)
of course, remember to close the doc with doc.Close() and quit Word with Word.Quit() later.
I am using two options. Good source for these operations is this book. Is quite older, but still has many good examples.
First:
from win32com.client import Dispatch
myWord = Dispatch('Word.Application')
myWord.Visible = 1 # comment out for production
myWord.Documents.Open(working_file) # open file
# ... doing something
myWord.ActiveDocument.SaveAs(new_file)
myWord.Quit() # close Word.Application
Second:
from win32com import client
app = client.gencache.EnsureDispatch("Word.Application")
app.Documents.Open(file) # open file
app.ActiveDocument.ActiveWindow.View.Type = 3 # prevent that word opens itself
app.Quit()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With