473,793 Members | 2,810 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Editing/Writing Word-Files from Python

Hi,

is it possible to edit or write Word-files out of a Python-Program?

thx in advance
daniel
Jul 18 '05 #1
4 4322
Daniel Cloutier wrote:
is it possible to edit or write Word-files out of a Python-Program?


Word uses a proprietary binary format, so you don't really
have as an option the simple "open file, make some changes,
write file" approach you might be picturing.

On the other hand, this *is* Python, so you have alternatives:

1. Use ActiveX and control Word from Python. This is described
well in Mark Hammond's book on Win32 programming with Python,
web pages (use Google), and posts in the comp.lang.pytho n archives.

2. Write HTML or RTF files, which are not proprietary binary
formats. These can be edited in Python and then written back
again. Not sure if there's an RTF library, but "it's just text".

3. Define in more detail what you are actually looking for
("edit" is ill-defined) including the context, and you'll
probably get another three or four ways of doing it.

-Peter
Jul 18 '05 #2
[Daniel Cloutier]
is it possible to edit or write Word-files out of a Python-Program?
If you have access to Office 2003, are feeling brave, and have a lot
of time on your hands, you could create and manipulate the XML
structures that Word 2003 uses.

It thought the group members might find it interesting to see such a
file, so I have exported a "Hello World!" document as XML, and posted
the result below. I had to tidy it up a little, the original came out
all on one line. And I had to add an encoding declaration :-)

In terms of generating such structures, well, everybody has their own
favourite *ML templating language. I'd use TAL or XSLT in "Literal
Result Element as Stylesheet" mode ...

http://www.w3.org/TR/xslt#result-element-stylesheet

#--------- helloworld.xml --- cut here ------------------------
<?xml version="1.0" encoding='utf-8'?>
<?mso-application progid="Word.Do cument"?>
<w:wordDocume nt
w:embeddedObjPr esent="no"
w:macrosPresent ="no"
w:ocxPresent="n o"
xml:space="pres erve"
xmlns:aml="http ://schemas.microso ft.com/aml/2001/core"
xmlns:dt="uuid: C2F41010-65B3-11d1-A29F-00AA00C14882"
xmlns:o="urn:sc hemas-microsoft-com:office:offi ce"
xmlns:sl="http://schemas.microso ft.com/schemaLibrary/2003/core"
xmlns:v="urn:sc hemas-microsoft-com:vml"
xmlns:w="http://schemas.microso ft.com/office/word/2003/wordml"
xmlns:w10="urn: schemas-microsoft-com:office:word "
xmlns:wx="http://schemas.microso ft.com/office/word/2003/auxHint" <o:DocumentProp erties>
<o:Title>Hell o World</o:Title>
<o:Author>Ala n</o:Author>
<o:LastAuthor>A lan</o:LastAuthor>
<o:Revision>1 </o:Revision>
<o:TotalTime> 1</o:TotalTime>
<o:Created>20 04-04-20T15:38:00Z</o:Created>
<o:LastSaved>20 04-04-20T15:39:00Z</o:LastSaved>
<o:Pages>1</o:Pages>
<o:Words>1</o:Words>
<o:Characters>1 2</o:Characters>
<o:Company>Alan </o:Company>
<o:Lines>1</o:Lines>
<o:Paragraphs>1 </o:Paragraphs>
<o:CharactersWi thSpaces>12</o:CharactersWit hSpaces>
<o:Version>11.6 113</o:Version>
</o:DocumentPrope rties>
<w:fonts>
<w:defaultFon ts
w:ascii="Times New Roman"
w:cs="Times New Roman"
w:fareast="Time s New Roman"
w:h-ansi="Times New Roman"
/>
</w:fonts>
<w:styles>
<w:versionOfBui ltInStylenames w:val="4"/>
<w:latentStyl es
w:defLockedStat e="off"
w:latentStyleCo unt="156"
/>
<w:style
w:default="on"
w:styleId="Norm al"
w:type="paragra ph" <w:name w:val="Normal"/>
<w:rPr>
<wx:font wx:val="Times New Roman"/>
<w:lang
w:bidi="AR-SA"
w:fareast="EN-GB"
w:val="EN-GB"
/>
</w:rPr>
</w:style>
<w:style
w:default="on"
w:styleId="Defa ultParagraphFon t"
w:type="charact er" <w:name w:val="Default Paragraph Font"/>
<w:semiHidden/>
</w:style>
<w:style
w:default="on"
w:styleId="Tabl eNormal"
w:type="table"

<w:name w:val="Normal Table"/>
<wx:uiName wx:val="Table Normal"/>
<w:semiHidden/>
<w:rPr>
<wx:font wx:val="Times New Roman"/>
</w:rPr>
<w:tblPr>
<w:tblInd w:type="dxa" w:w="0"/>
<w:tblCellMar >
<w:top w:type="dxa" w:w="0"/>
<w:left w:type="dxa" w:w="108"/>
<w:bottom w:type="dxa" w:w="0"/>
<w:right w:type="dxa" w:w="108"/>
</w:tblCellMar>
</w:tblPr>
</w:style>
<w:style w:default="on" w:styleId="NoLi st" w:type="list">
<w:name w:val="No List"/>
<w:semiHidden/>
</w:style>
</w:styles>
<w:docPr>
<w:view w:val="print"/>
<w:zoom w:percent="100"/>
<w:doNotEmbedSy stemFonts/>
<w:proofState w:grammar="clea n" w:spelling="cle an"/>
<w:attachedTemp late w:val=""/>
<w:defaultTabSt op w:val="720"/>
<w:displayHoriz ontalDrawingGri dEvery w:val="0"/>
<w:displayVerti calDrawingGridE very w:val="0"/>
<w:useMarginsFo rDrawingGridOri gin/>
<w:characterSpa cingControl w:val="DontComp ress"/>
<w:optimizeForB rowser/>
<w:validateAgai nstSchema/>
<w:saveInvalidX ML w:val="off"/>
<w:ignoreMixedC ontent w:val="off"/>
<w:alwaysShowPl aceholderText w:val="off"/>
<w:compat>
<w:footnoteLayo utLikeWW8/>
<w:shapeLayoutL ikeWW8/>
<w:alignTablesR owByRow/>
<w:forgetLastTa bAlignment/>
<w:doNotUseHTML ParagraphAutoSp acing/>
<w:layoutRawTab leWidth/>
<w:layoutTableR owsApart/>
<w:useWord97Lin eBreakingRules/>
<w:dontAllowFie ldEndSelect/>
<w:useWord2002T ableStyleRules/>
</w:compat>
</w:docPr>
<w:body>
<wx:sect>
<w:p>
<w:pPr>
<w:jc w:val="center"/>
<w:rPr>
<w:sz w:val="40"/>
<w:sz-cs w:val="40"/>
</w:rPr>
</w:pPr>
<w:r>
<w:rPr>
<w:sz w:val="40"/>
<w:sz-cs w:val="40"/>
</w:rPr>
<w:t>Hello World!</w:t>
</w:r>
</w:p>
<w:sectPr>
<w:pgSz w:h="16838" w:w="11906"/>
<w:pgMar
w:bottom="1440"
w:footer="720"
w:gutter="0"
w:header="720"
w:left="1800"
w:right="1800"
w:top="1440"
/>
<w:cols w:space="720"/>
</w:sectPr>
</wx:sect>
</w:body>
</w:wordDocument>
#--------- helloworld.xml --- cut here ------------------------

--
alan kennedy
------------------------------------------------------
check http headers here: http://xhaus.com/headers
email alan: http://xhaus.com/contact/alan
Jul 18 '05 #3
Daniel Cloutier <da************ @yahoo.com> wrote in message news:<c6******* *****@ID-47444.news.uni-berlin.de>...

is it possible to edit or write Word-files out of a Python-Program?


Yes.

(a) You need the win32all modules from Mark Hammond.

(b) To try out the object model of MS Word, press ALT+F11 to bring up
the VBA environment, then F2 to view the object browser. It's a
complicated subject.

-------------------------------------------
import pythoncom
from win32com.client import Dispatch

app = Dispatch('Word. Application')
app.Visible = 1
doc = app.Documents.A dd()
s = doc.Sentences(1 )
s.Text = 'This is a test.'
doc.SaveAs('C:\ \mydoc2.doc')
app.Quit()

app = None
pythoncom.CoUni nitialize()
--------------------------------------------

You may want to add better exception handling, otherwise, you may
often have danggling processes when exceptions happen. (You'll then
have to manually kill them from the task manager.)

regards,

Hung Jung
Jul 18 '05 #4
Hung Jung Lu wrote:
Daniel Cloutier <da************ @yahoo.com> wrote in message news:<c6******* *****@ID-47444.news.uni-berlin.de>...
is it possible to edit or write Word-files out of a Python-Program?

Yes.

(a) You need the win32all modules from Mark Hammond.

(b) To try out the object model of MS Word, press ALT+F11 to bring up
the VBA environment, then F2 to view the object browser. It's a
complicated subject.

-------------------------------------------
import pythoncom
from win32com.client import Dispatch

app = Dispatch('Word. Application')
app.Visible = 1
doc = app.Documents.A dd()
s = doc.Sentences(1 )
s.Text = 'This is a test.'
doc.SaveAs('C:\ \mydoc2.doc')
app.Quit()

app = None
pythoncom.CoUni nitialize()
--------------------------------------------

You may want to add better exception handling, otherwise, you may
often have danggling processes when exceptions happen. (You'll then
have to manually kill them from the task manager.)

regards,

Hung Jung


thanks a lot, yesterday i found out myself that i have to use the
win32com package, but i didn't know how to add some text

greetings
daniel
Jul 18 '05 #5

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

26
3066
by: Miguel Orrego | last post by:
Hi, Can anybody recommend a good freeware WYSIWYG editor with code view as well? Thanks.
21
2083
by: webmaster | last post by:
Hi all, Without opening a HUGE can of worms, I just wanted to get some ideas of what others are using professionally to create websites commercially. For years I had used Homesite and never migrated to Dreamweaver or ColdFusion. My limited abilities notwithstanding, I have moved to FrontPage 2000 (forget validation) and now to MS Publisher. Am I essentially bringing a knife to a gun fight here? I have a very limited budget and want to...
9
2099
by: jerry.upstatenyguy | last post by:
I am really stuck on this. I am trying to write a string array containing a "word" and a "definition" to a class called Entry. Ultimately this will end up in another class called dictionary. No, this is not a homework assignment. In fact it was a question on my class midterm that everyone bombed. Unfortunately we never covered this in class prior to the midterm. Anyway, please help if you would be so kind. Here is what I have. I...
12
1815
by: dino d. | last post by:
hi everyone- my subject pretty much says it all- is there a secure way to do this? the non-secure ways are, as i understand it, to populate a listbox with indices as names, or maybe use a hidden control. is the only secure way with sessions? i was also thinking about perhaps creating a meta table that says who is editing which record right now. any advice? thanks, dino
4
2531
by: Mike De Petris | last post by:
I am using itextsharp to fill in and flatten some fields from data filled in a web form field and all works quite well. The question now is how to manage the pdf template that has the fields to be filled, changing it in acrobat is slow and difficult as there are no word processing tools. I tryed Foxit PDF Editor but cannot find a way to name the form fields. Is there a way to mantain a source document, for example in Word and...
5
2319
by: sara | last post by:
Hi - I have 2 new questions in a new database I'm trying to develop. The first has 6 fields on a table and allows the user to enter them on a form. The form is bound to the table. All 6 fields are default value = 0 on the table and on the form. Fields are filled in at different times and maybe by different people, so I wanted them all to "initialize" to 0.
12
2593
by: Trish | last post by:
I just had a bad experience using MS Word as an HTML editor. It bloated more than 200% so I could barely recognize the essential statements; and it introduced more than 14,000 errors. Also, although it displayed fine in Firefox, it was unintelligible to IE. I spent the day trying to reduce the errors to the point wherel HTML Tidy could finish a pass without aborting. Finally I succeeded. No errors. It displays fine in Firefox & IE. ...
10
2856
by: PhilSorum | last post by:
Hi all. I've to edit a txt file, deleting a given word. My approach is to open the file and read it char by char, copying that to a second file. I use a buffer to identify the given word, so if I recognize the pattern I don't pass it to the new file. Finally I copy the new file to the former. Is there a better way to carry out my task, maybe editing "in loco" (without using a support file)? Before opening the file I know in which...
1
4192
by: atta | last post by:
hi all i am confronted with a problem where i have to submit a word document to my boss who will edit it and return it to me for printing etc.i am using iis 6 and uploading the file to server from where my boss opens up in his web page and edits and then marks it to me.i have no idea how to do that.i have a page where a link to the required file is created and it opens up in ms word but read only mode . i want it to open with full functionality...
1
1473
ganesanji
by: ganesanji | last post by:
hi to all, I am new to php. I have to edit a text file using php. I saw the file system concepts modes. My problem is I want to change a particular text or word in a text file. How to find the index of the specific word. Is there any functions or methods available for change a particular word or finding index of a word... For the example, consider a text file named ganesh.txt which content is shown below.... ganesh is working ...
0
9518
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10433
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10212
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10161
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
10000
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
5436
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
4112
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3720
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2919
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.