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

Andrew Robert andrew.arobert at gmail.com
Thu Jul 20 19:25:26 CEST 2006


-----BEGIN PGP SIGNED MESSAGE-----

Hash: SHA1



Hi Everyone,

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.

The download from web is relatively painless.

#!C:\Python24\Python
import sys
from urllib import urlopen


if  len(sys.argv) == 1 :
	print "\nUsage:   getkwik.py  {output file name} \n"
else:
   open(sys.argv[1],"wb").write( urlopen("http://mydomain/file.txt").read() )

Trying to get the file to word is a little more troubling.


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?




import sys
import time
import string
import win32com.client

# --------------------------------------------------------------------
class CWordAutomate:
    """Encapsulates a winword com connection"""
    def __init__( self ):
        """construct: create OLE connection to winword"""
        self.m_obWord         = win32com.client.Dispatch( "Word.Application" )
        self.m_obDoc          = self.m_obWord.Documents.Add( ) # create new doc
        self.m_obWord.Visible = 1
        self.m_Sel            = self.m_obWord.Selection # get a selection

    def WriteLine( self, sTxt, sFont, lSize, bBold=0 ):
        """Write a line to winword"""
        self.m_Sel.Font.Name = sFont
        self.m_Sel.Font.Bold = bBold
        self.m_Sel.Font.Size = lSize
        self.m_Sel.TypeText( Text=sTxt + "\n"  )

# --------------------------------------------------------------------

# - open a file
sFileName  = sys.argv[1]
obFile     = file( sFileName, 'r+' )
sContent   = obFile.read()
obFile.close()
lstContent = sContent.splitlines()

# - display contents in word
obWord = CWordAutomate()
obWord.WriteLine( "Content of the file " + sFileName, "Times New Roman", 18, 1 )
for sLine in lstContent:
    obWord.WriteLine( sLine, "Courier New", 10  )
sLastMsg = time.strftime( "document generated on %c", time.localtime()  )
obWord.WriteLine( sLastMsg, "Times New Roman", 14, 0 )

-----BEGIN PGP SIGNATURE-----

Version: GnuPG v1.2.1 (MingW32)

Comment: GnuPT 2.7.2



iD8DBQFEv7yGDvn/4H0LjDwRAiPPAKCi4LCSuB0qobKavoKqZZ13E7grbwCgriQ8

Bz4uP7IcwipZdfSUUFDi9Hg=

=C1Gx

-----END PGP SIGNATURE-----



More information about the Tutor mailing list