Python: Writing text to a 2003 Word Doc in a specific place on the page

227 Views Asked by At

I'm using Python 2.7, Windows 7, and Word 2003. Those three cannot change (well except for maybe the python version). I work in Law and the attorneys have roughly 3 boiler plate objections (just a large piece of text, maybe 5 paragraphs) that need to be inserted into a word document at a specific spot. Now instead of going through and copying and pasting the objection where its needed, my idea is for the user to go through the document adding a special word/phrase (place holder if you will) that wont be found anywhere in the document. Then run some code and have python fill in the rest. Maybe not the cleverest way to go about it, but I'm a noob. I've been practicing with a test page and inserted the below text as place holders (the extra "o" stands for objection)

oone

otwo

othree

Below is what I have so far. I have two questions

  1. Do you have any other suggestions to go about this?
  2. My code does insert the string in the correct order, but the formatting goes out the window and it writes in my string 6 times instead of 1. How can I resolve the formatting issue so it simply writes the text into the spot the place holder is at?

    import sys
    import fileinput
    f = open('work.doc', 'r+')
    obj1 = "oone"
    obj2 = "otwo"
    obj3 = "othree"
    for line in fileinput.input('work.doc'):
        if obj1 in line:
            f.write("Objection 1")
        elif obj2 in line:
            f.write("Objection 2")
        elif obj3 in line:
            f.write("Objection 3")
        else:
            f.write("No Objection")
    f.close
    
1

There are 1 best solutions below

2
Nishant Srivastava On

You could use python-uno to load the document into OpenOffice and manipulate it using the UNO interface. There is some example code on the site I just linked to which can get you started.