Controlling SaveAs Word 9.0 COM

Jim Abrams jim at publishingresources.com
Fri Apr 27 15:12:11 EDT 2001


Mark Sloboda <denchan at earthlink.net> wrote in
<mailman.988385621.26593.python-list at python.org>: 

> Hello,
> I have to open a Word file which is text, save it as DOS-encoded text
> under a different name, and close it.
> A similar VB code example is:
> myDocname = ActiveDocument.Name
> pos = InStr(myDocname, ".")
> If pos > 0 Then
> myDocname = Left(myDocname, pos -1)
> myDocname = myDocname & ".txt"
> ActiveDocument.SaveAs FileName:=myDocname, FileFormat:=wdFormatText
> End If
> 
> In my Python code I have tried several approaches:
> from win32com.client import Dispatch
> 
> Word = Dispatch("Word.Application")
> Word.Visible = 1
> 
> WordDoc = Word.Documents.Open("C:\\test.txt")
> WordDoc.SaveAs(FileName='C:\\TextTest2.txt',FileFormat='wdFormatDOSText'
> ) WordDoc.Close()
> Word.Quit()
> 
> It works fine if I leave the FileFormat argument out. However, when I
> add the FileFormat argument as shown above, I get
> 
> Traceback (most recent call last):
> File "d:\python20\pythonwin\pywin\framework\scriptutils.py", line 301,
> in RunScript
> exec codeObject in __main__.__dict__
> File "C:\...\OpenApp.py", line 7, in ?
> WordDoc.SaveAs(FileName='C:\\TextTest2.txt',FileFormat='wdFormatDOSText'
> ) File
> "d:\python20\win32com\gen_py\00020905-0000-0000-C000-000000000046x0x8x1.
> py", line 13959, in SaveAs
> return self._oleobj_.InvokeTypes(0x66, LCID, 1, (24, 0), ((16396, 17),
> (16396, 17), (16396, 17), (16396, 17), (16396, 17), (16396, 17),
> (16396, 17), (16396, 17), (16396, 17), (16396, 17), (16396,
> 17)),FileName, FileFormat, LockComments, Password, AddToRecentFiles,
> WritePassword, ReadOnlyRecommended, EmbedTrueTypeFonts,
> SaveNativePictureFormat, SaveFormsData, SaveAsAOCELetter)
> com_error: (-2147352571, 'Type mismatch.', None, 2)

The file format param is an integer. 
You can get access to all the constants with:

>>> import win32com.client
>>> w = win32com.client.Dispatch("Word.Application")
>>> w
<win32com.gen_py.Microsoft Word 9.0 Object Library._Application>
>>> win32com.client.constants.wdFormatDOSText
4
>>> 

Before that will work you need to find the makepy.py script 
(Python\win32com\client\makepy.py)

and run it. From the list choose the Microsoft Word 9 Type library.

Then the above code should work and you can use 
win32com.client.constants.wdFormatDOSText as the parameter you need.

Hope this helps, 

-J





More information about the Python-list mailing list