[Tutor] Using python to create and save a Ms Word file

andrew clarke mail at ozzmosis.com
Thu Jul 20 20:12:28 CEST 2006


On Thu, Jul 20, 2006 at 01:25:26PM -0400, Andrew Robert wrote:

> I have a text file being broadcast on a web site and I would like to download it 
> and save it as an MS Word file.

...

> I found the following code on the web that comes close to what i need.
> 
> It:
> 
> - - reads a file passed to it
> - - opens word file 
> - - dumps the read contents to the file
> - - places a time stamp at the end signaling when the conversion occured
> 
> What is is missing is how to automate saving/closing the file when the conversion is complete.
> 
> Would someone be able to help fill in the blanks on this?

I've never played with Win32 COM before, but your message inspired me to
learn.  :-)

A quick Google later, and it seems you need to add the following methods
to the CWordAutomate class:

    def Save(self, sFilename):
        self.m_obDoc.SaveAs(sFilename)

    def Quit(self):
        self.m_obWord.Quit()

Then in your code:

> sLastMsg = time.strftime( "document generated on %c", time.localtime()  )
> obWord.WriteLine( sLastMsg, "Times New Roman", 14, 0 )

Add these:

obWord.Save("blah.doc")
obWord.Quit()

On my system, "blah.doc" was saved as

C:\Documents and Settings\ozzmosis\My Documents\blah.doc

So you'll need to specify an absolute pathname if you want it to be
saved somewhere else.

I picked this up from:

http://mail.python.org/pipermail/python-win32/2002-June/000396.html

I guess we both need to subscribe to the python-win32 mailing list...  ;-)

Regards
Andrew


More information about the Tutor mailing list