'I would like to edit an odt document using python. Just a simple swap of keywords. Is this possible?

1)I would like to swap certain keywords in an odf document programmatically. For example, the sample lease has TENANT_NAME, and my program would insert the actual name of the tenant.

  1. I have tried a code snippet from this website that works on simple documents, but when I try to use it on my lease it throws an index out of range error.
from odf import opendocument, text, teletype

this_dictionary = {
    'TENANT_NAME': 'Cameron Stark',
    'DATE_START': '5/1/2022',
    'DATE_END': '7/31/2022',
    'RENT_AMOUNT': '500',
    'DEPOSIT_AMOUNT': '400',
    'EMAIL_ADDRESS': '[email protected]',
    'PHONE_NUMBER': '1234567890'
}

PATH = "C:/Users/Cameron Stark/Documents/sample_lease_alpine.odt"
DESTINATION = "C:/Users/Cameron Stark/Documents/cameron_lease.odt"


def change_odt_file(my_dictionary, path, destination):
    text_doc = opendocument.load(path)
    for x, y in my_dictionary.items():
        texts = text_doc.getElementsByType(text.P)
        s = len(texts)
        for i in range(s):
            old_text = teletype.extractText(texts[i])
            new_text = old_text.replace(x, y)
            new_S = text.P()
            new_S.setAttribute("stylename", texts[i].getAttribute("stylename"))
            new_S.addText(new_text)
            texts[i].parentNode.insertBefore(new_S, texts[i])
            texts[i].parentNode.removeChild(texts[i])
        text_doc.save(destination)
        text_doc = opendocument.load(destination)


change_odt_file(this_dictionary, PATH, DESTINATION)


Solution 1:[1]

Simple solution, just re-write my lease in HTML. Super easy to work with and more capability than any word-processing software.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Cameron Stark