Skip to content Skip to sidebar Skip to footer

Opening A Ms Word File In Pywin32

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\Docum

Solution 1:

You need to open the file from the correct location.

You might try this:

import win32com.client as win32
importosword= win32.gencache.EnsureDispatch('Word.Application')
word.Visible = Falsedoc_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.

Solution 2:

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

Solution 3:

I suggest this method:

>>>import win32api>>>win32api.ShellExecute(0, 'open', 'D:\\test.docx', '', '', 1)

This will open the file (.docx or any other types) by default program (e.g. Microsoft Word).

Solution 4:

Having the same problem I just changed all slahes '/' in address-string to double-back-slashes: '\\'. Everything worked out well.

Post a Comment for "Opening A Ms Word File In Pywin32"