O'Reilly logo

Python Programming On Win32 by Mark Hammond, Andy Robinson

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

A Simple Example

Let’s start with the simplest possible example:

from win32com.client import Dispatch
MYDIR = 'c:\\data\\project\\oreilly\\examples\\ch12_print'

def simple():
    myWord = Dispatch('Word.Application')
    myWord.Visible = 1  # comment out for production
    
    myDoc = myWord.Documents.Add()
    myRange = myDoc.Range(0,0)
    myRange.InsertBefore('Hello from Python!')
    
    # uncomment these for a full script
    #myDoc.SaveAs(MYDIR + '\\python01.doc')
    #myDoc.PrintOut()
    #myDoc.Close()

When you execute this function, Word starts, and your message is displayed. We’ve commented out the lines at the bottom, but you can choose to print, save, or close the document. It’s fun to arrange the Python console and Word side-by-side and watch your text appearing, and a great way to learn the Word object model.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required